管道定义类似,就是key都要加上引号
pipeline = [
{
'$match': {'InnerMark': 'No'}
},
{
'$project': {
"D": "$DiskSpace",
"M": "$MemoryLimit",
'cmp': {
'$and': [
{
'$lte': ["$BusinessCreateMonth", month]
},
{
'$or': [
{'$gt': ["$BusinessDeleteMonth", month]},
{'$eq': ['$DeleteTime', None]}
]
}
]
}
}
},
{
'$match': {'cmp': True}
},
{
'$group': {
'_id': "$cmp",
'count': {'$sum': 1},
'disk_count': {'$sum': '$D'},
'memory_count': {'$sum': '$M'}
}
}
]
# 创建游标,这里的_get_collection是受保护对象(上下是一样的的,注意那个星号)
cur = Db._get_collection().aggregate(pipeline)
cur = Db.objects().aggregate(*pipeline)
# 聚合结果存下来
result = cur.next()
# 关闭游标
cur.close()
# 返回结果
return result

本文介绍了一个具体的MongoDB聚合管道示例,展示了如何使用$match、$project、$group等阶段来过滤和处理数据,实现复杂的查询需求。通过具体代码说明了如何创建游标进行数据聚合,并将结果保存及返回。

1218

被折叠的 条评论
为什么被折叠?



