Python中如何使用MongoDB的aggregate对多个字段进行求和?

我的数据结构是这样的:

{
    "_id": "xxxxxx",
    "detail": {
        "product_name": "swords  big",
        "type": "weapon",
        "make_player": "震荡龙",
        "game_zone": 1
    }
}

我想统计detail中的数据的多个值的 总和 ,能输出成这样的效果:

{” game_zone “:1000,  ” type “:200}

怎么写语句可以实现呢?


Python中如何使用MongoDB的aggregate对多个字段进行求和?

10 回复

直接$match 再$group 不就可以了?


from pymongo import MongoClient

# 连接MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['your_database']
collection = db['your_collection']

# 聚合管道
pipeline = [
    {
        '$group': {
            '_id': None,  # 不分组,对所有文档聚合
            'total_field1': {'$sum': '$field1'},
            'total_field2': {'$sum': '$field2'},
            'total_field3': {'$sum': '$field3'}
        }
    }
]

# 执行聚合
results = list(collection.aggregate(pipeline))

# 输出结果
if results:
    totals = results[0]
    print(f"字段1总和: {totals['total_field1']}")
    print(f"字段2总和: {totals['total_field2']}")
    print(f"字段3总和: {totals['total_field3']}")
else:
    print("没有找到数据")

# 如果要按某个字段分组求和,比如按category字段分组:
group_pipeline = [
    {
        '$group': {
            '_id': '$category',  # 按category分组
            'total_sales': {'$sum': '$sales'},
            'total_profit': {'$sum': '$profit'}
        }
    },
    {'$sort': {'_id': 1}}  # 可选:按分组字段排序
]

group_results = list(collection.aggregate(group_pipeline))
for item in group_results:
    print(f"分类: {item['_id']}, 销售总额: {item['total_sales']}, 利润总额: {item['total_profit']}")

核心就三步:1)用$group阶段指定分组字段(_id),2)用$sum运算符对每个字段求和,3)通过aggregate()执行管道。如果要对所有文档求和而不分组,_id设为None就行。

简单说就是$group$sum组合搞定多字段求和。

.aggregate([{$match:{}}, {$group:{_id:null, total:{$sum:"$detail.game_zone"}}}])

$sum 求总数只能求一个值

{$group: {_id: “$detail.type”, sum: {$sum: “$detail.game_zone”}}} ?

比如: type: 1 我要得到 sum,game_zone:2 的我要得到一个 sum

你这是听谁说的= = 几个值都可以的
.aggregate([{$match:{}}, {$group:{_id:null, type:{$sum:"$detail.type"}},game_zone:{$sum:"$detail.game_zone"}}}])

括号写错了 不过差不多就是这个意思了

这不是在文档里面就有的吗……

文档没写统计两个值啊

回到顶部