如何在MongoDB聚合中使用$count与$group按国家分组统计status
实现思路与代码
- 核心逻辑分两步分组完成:先联合统计「国家+状态」的组合计数,再按国家维度聚合组装成目标格式
- 优势:无需提前枚举
status字段的所有可选值,后续新增状态类型不需要调整查询逻辑
完整聚合查询
db.collection.aggregate([ // 1. 联合country和status分组,统计每个组合的出现次数 { $group: { _id: { country: "$country", status: "$status" }, count: { $sum: 1 } } }, // 2. 按country单独分组,收集同国家下所有状态的计数键值对 { $group: { _id: "$_id.country", statusPairs: { $push: { k: "$_id.status", v: "$count" } } } }, // 3. 将键值对数组转换为对象,得到最终的status字段格式 { $project: { status: { $arrayToObject: "$statusPairs" } } } ])
中间结果说明
第一步分组后输出:
[ { _id: { country: 'US', status: 'ordered' }, count: 1 }, { _id: { country: 'UK', status: 'ordered' }, count: 1 }, { _id: { country: 'UK', status: 'shipped' }, count: 1 } ]第二步分组后输出:
[ { _id: 'US', statusPairs: [ { k: 'ordered', v: 1 } ] }, { _id: 'UK', statusPairs: [ { k: 'ordered', v: 1 }, { k: 'shipped', v: 1 } ] } ]第三步转换后就得到你需要的目标输出。
内容的提问来源于stack exchange,提问作者bluepuma77
相关产品推荐
相关产品推荐

