MongoDB聚合$group搭配$map使用异常,无法正确统计每日订单数与总金额
问题原因分析
- 自定义变量引用错误:
$map中通过as定义的临时变量item,需要使用$$item的格式引用,你写的$item会去查询文档根路径下的item字段,该字段不存在,计算结果为null,最终累加得到0。 - 单订单金额计算逻辑缺失:
$map返回的是每个商品的金额数组,需要先对单订单内的所有商品金额求和,再汇总到全局总金额中。
解决方案1:不使用$unwind(推荐,性能更优)
直接通过$reduce先计算每个订单的总金额,再分组统计:
db.getCollection("orders").aggregate([ { $group: { _id: { date: { $dayOfMonth: "$createdAt" }, month: { $month: "$createdAt" }, year: { $year: "$createdAt" } }, count: { $sum: 1 }, totalPrice: { $sum: { $reduce: { input: "$items", initialValue: 0, in: { $add: ["$$value", { $multiply: ["$$this.price", "$$this.quantity"] }] } } } } } } ])
如果想沿用$map的写法,修正变量引用后也可以生效:
totalPrice: { $sum: { $sum: { $map: { input: "$items", as: "item", in: { $multiply: ["$$item.price", "$$item.quantity"] } } } } }
这里内层的$sum用于计算单订单所有商品的金额总和,外层的$sum用于分组时累加所有订单的总金额。
解决方案2:使用$unwind,修正订单计数
如果要使用$unwind拆分items数组,需要在分组时通过去重统计订单ID的方式计算订单数量,避免拆分后重复计数:
db.getCollection("orders").aggregate([ { $unwind: "$items" }, { $group: { _id: { date: { $dayOfMonth: "$createdAt" }, month: { $month: "$createdAt" }, year: { $year: "$createdAt" } }, count: { $addToSet: "$_id" }, totalPrice: { $sum: { $multiply: ["$items.price", "$items.quantity"] } } } }, { $addFields: { count: { $size: "$count" } } } ])
内容的提问来源于stack exchange,提问作者Manga Arun
相关产品推荐
相关产品推荐

