python - 如何使用 MongoEngine 运行这个 MongoDB 查询

标签 python mongodb mongodb-query aggregation-framework mongoengine

我不知道 MongoEngine 是否支持聚合框架。

是否可以使用 MongoEngine 运行此查询?

db.collection.aggregate([
    { "$group": {
        "_id": {
            "year": { "$year": "$utc_timestamp" },
            "month": { "$month": "$utc_timestamp" },
            "day": { "$dayOfMonth": "$utc_timestamp" },
        },
        "defects": {
            "$sum": { "$cond": [
                { "$eq": [ "$status", "defect" ] },
                1,
                0
            ]}
        },
        "totalCount": { "$sum": 1 }
    }},
    { "$project": {
        "defect_rate": {
            "$cond": [
                { "$eq": [ "$defects", 0 ] },
                0,
                { "$divide": [ "$defects", "$totalCount" ] }
            ]
        }
    }}
])

如果没有,我可以通过 MongoEngine 直接(原始)运行它吗?

最佳答案

您可以使用类上的 ._get_collection() 方法获取由 pymongo 驱动程序实现的原始“集合”对象。

Class._get_collection().aggregate([
    { '$group': {
        '_id': {
            'year': { '$year': '$utc_timestamp' },
            'month': { '$month': '$utc_timestamp' },
            'day': { '$dayOfMonth': '$utc_timestamp' },
        },
        'defects': {
            '$sum': { '$cond': [
                { '$eq': [ '$status', 'defect' ] },
                1,
                0
            ]}
        },
        'totalCount': { '$sum': 1 }
    }},
    { '$project': {
        'defect_rate': {
            '$cond': [
                { '$eq': [ '$defects', 0 ] },
                0,
                { '$divide': [ '$defects', '$totalCount' ] }
            ]
        }
    }}
])

关于python - 如何使用 MongoEngine 运行这个 MongoDB 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24155429/

相关文章:

mongodb - 考虑到新的索引交集功能,复合索引何时在 MongoDB 2.6 中仍然相关?

javascript - 当翻译在另一个集合中时,如何在 MongoDB 上处理 i18n(带回退)?

node.js - Mongoose 中的 friend 模式建模?

c# - 使用 ElemMatch 的 ArgumentNullException

python - 为什么使用 fromkeys 初始化列表字典会影响列表追加方式

python - 在类级容器初始化中调用静态方法

python - SQLAlchemy 和 django,准备好生产了吗?

javascript - Mongo find() 生成 {} 以及预期结果

arrays - 带有嵌套文档的 $lookup

python - 升级python3时pip出现问题