如何编写MongoDB group by聚合管道实现分类计数与剩余类型合并
MongoDB 指定规则分组统计聚合实现
需求
现有MongoDB集合内的文档统一包含type字段,取值覆盖software、hardware、network、test等多类,需要通过聚合管道完成分组统计,最终仅返回3项统计结果:
- 单独统计software类型的文档总数
- 单独统计hardware类型的文档总数
- 将两类以外的所有type对应文档合并,统一汇总为_id为other的统计项
实现代码
在目标集合上执行如下聚合管道逻辑即可:
db.目标集合名.aggregate([ { $group: { // 按自定义规则映射文档所属统计分组 _id: { $switch: { branches: [ { case: { $eq: ["$type", "software"] }, then: "software" }, { case: { $eq: ["$type", "hardware"] }, then: "hardware" } ], default: "other" } }, // 累计每个分组的文档数量 count: { $sum: 1 } } }, { // 给每个分组设置固定排序权重,匹配要求的返回顺序 $addFields: { sortWeight: { $switch: { branches: [ { case: { $eq: ["$_id", "software"] }, then: 1 }, { case: { $eq: ["$_id", "hardware"] }, then: 2 } ], default: 3 } } } }, // 按权重升序排列,保证返回顺序为software、hardware、other { $sort: { sortWeight: 1 } }, // 移除临时使用的排序权重字段 { $project: { sortWeight: 0 } } ])
实际效果
针对给出的示例文档集(2条software、1条hardware、1条network、1条test),管道执行后的返回结果完全匹配预期格式:
[ {"_id": "software", "count": 2}, {"_id": "hardware", "count": 1}, {"_id": "other", "count": 2} ]
补充说明:如果不需要严格限制结果返回顺序,仅要求统计三个分组的数值,可省略排序、字段投影的三个阶段,聚合过程会直接返回对应分组的计数结果。
内容的提问来源于stack exchange,提问作者sandy
相关产品推荐
相关产品推荐

