如何统计MongoDB aggregate聚合查询返回的所有分组结果的总数量?
MongoDB聚合新增总告警数字段解决方案
方案1:兼容MongoDB 3.4及以上版本
通过$facet算子并行执行两组聚合逻辑,分别计算分组明细和总告警数后合并输出:
db.getCollection('alerts').aggregate([ { $match: { houseId: ObjectId("609100a56ed9f8001351aee3") } }, { $facet: { // 原有按告警类型分组的逻辑 "type_groups": [ { $group: { _id: '$type', count: { $sum: 1 }, alerts: { $push: { _id: '$_id', type: '$type' } } } } ], // 计算总告警数 "total_count": [ { $count: "total" } ] } }, // 展开分组明细 { $unwind: "$type_groups" }, // 展开总数 { $unwind: "$total_count" }, // 调整输出字段结构 { $project: { _id: "$type_groups._id", count: "$type_groups.count", alerts: "$type_groups.alerts", total: "$total_count.total" } } ])
方案2:MongoDB 5.0及以上版本极简写法
使用窗口函数直接统计全部分组的count总和,无需调整原有聚合逻辑:
db.getCollection('alerts').aggregate([ { $match: { houseId: ObjectId("609100a56ed9f8001351aee3") } }, { $group: { _id: '$type', count: { $sum: 1 }, alerts: { $push: { _id: '$_id', type: '$type' } } } }, // 窗口函数计算所有分组的count总和 { $set: { total: { $sum: "$count", $window: { documents: ["unbounded", "unbounded"] } } } } ])
两种方案输出结果均符合预期,示例返回如下:
[{ "_id" : "cool", "count" : 1.0, "alerts" : [ { "_id" : ObjectId("61387e740dc3d853f1eee5b0"), "type" : "cool" } ], "total": 3.0 }, { "_id" : "hot", "count" : 2.0, "alerts" : [ { "_id" : ObjectId("61387e740dc3d853f1eee5b0"), "type" : "hot" }, { "_id" : ObjectId("61387e740dc3d853f1eee5b0"), "type" : "hot" } ], "total": 3.0 }]
内容的提问来源于stack exchange,提问作者Chicky
相关产品推荐
相关产品推荐

