如何使用MongoDB聚合查询实现指定的商品统计结果?
MongoDB聚合查询:按门店统计指定商品数量
现有数据库数据
[ { store: "s1", prod: "a" }, { store: "s2", prod: "b" }, { store: "s3", prod: "a" }, { store: "s2", prod: "c" }, { store: "s5", prod: "a" }, { store: "s3", prod: "b" }, { store: "s5", prod: "a" }, { store: "s1", prod: "c" } ]
期望聚合结果
[ { store: "s1", a: 1, b: 0, c: 1 }, { store: "s2", a: 0, b: 1, c: 1 } ]
原管道问题分析
你写的聚合管道存在两个核心问题:
$group的_id设为null,会把所有匹配的记录合并成一组,无法按门店单独统计;a字段的$sum: 1没有区分商品类型,统计的是分组内的总记录数,而非指定商品的数量。
正确聚合管道
[ // 筛选目标门店数据 { $match: { store: { $in: ["s1", "s2"] } } }, // 按门店分组,统计各商品数量 { $group: { _id: "$store", a: { $sum: { $cond: [{ $eq: ["$prod", "a"] }, 1, 0] } }, b: { $sum: { $cond: [{ $eq: ["$prod", "b"] }, 1, 0] } }, c: { $sum: { $cond: [{ $eq: ["$prod", "c"] }, 1, 0] } } } }, // 调整输出结构,去掉_id并映射store字段 { $project: { _id: 0, store: "$_id", a: 1, b: 1, c: 1 } } ]
步骤说明
- $match阶段:精准筛选出门店为
s1和s2的记录,减少后续计算的数据量; - $group阶段:以
store作为分组键(_id: "$store"),对每个分组内的记录,用$cond条件判断当前记录的prod是否等于目标商品,符合则累加1,否则累加0,最终得到每个门店各商品的数量; - $project阶段:移除默认生成的
_id字段,将分组键_id重命名为store,确保输出结构与期望结果完全一致。
内容的提问来源于stack exchange,提问作者muezz
相关产品推荐
相关产品推荐

