Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run this MongoDB query using MongoEngine

I can't tell if MongoEngine supports the aggregate 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) through MongoEngine?

like image 852
okoboko Avatar asked Jun 11 '14 05:06

okoboko


1 Answers

You can get the raw "collection" object as implemented by the pymongo driver using the ._get_collection() method on 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' ] }
            ]
        }
    }}
])
like image 117
Neil Lunn Avatar answered Oct 19 '22 23:10

Neil Lunn