How to run this MongoDB query using MongoEngine

I can’t say if MongoEngine supports a common framework.

Is it possible to run this query using 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" ] }
            ]
        }
    }}
])

If not, can I just run it directly (raw) via MongoEngine?

+4
source share
1 answer

You can get the original collection object implemented with the pymongo driver using the ._get_collection () method in the class.

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' ] }
            ]
        }
    }}
])
+7
source

Source: https://habr.com/ru/post/1544087/


All Articles