如何使用MongoEngine运行这个MongoDB查询
我不太确定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来执行这个查询吗?
1 个回答
8
你可以通过这个类里的 ._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' ] }
]
}
}}
])