如何利用MongoDB+Mongoose按sellerId计算卖家订单总收入?
按sellerId计算卖家订单总金额的MongoDB聚合方案
核心思路
由于sellerId嵌套在订单的products数组中,需先拆解数组建立卖家与订单金额的关联,再按卖家ID分组求和:
- 拆解数组:用
$unwind将每个订单的products数组拆分为单独文档,确保每个sellerId对应一条订单记录; - 分组求和:通过
$group按sellerId分组,累加对应订单的amount得到总金额; - 字段优化(可选):用
$project调整输出字段名,让结果更直观。
Mongoose代码实现
Order.aggregate([ // 拆解products数组,每个product生成独立文档 { $unwind: "$products" }, // 按sellerId分组,计算总金额与总税费 { $group: { _id: "$products.sellerId", totalAmount: { $sum: "$amount" }, totalTax: { $sum: "$tax" } } }, // 重命名字段,隐藏默认_id { $project: { sellerId: "$_id", totalAmount: 1, totalTax: 1, _id: 0 } } ]) .then(result => console.log(result)) .catch(err => console.error(err));
输出结果
基于你提供的订单数据,执行后会得到:
[ { "sellerId": "6360c6ed05e1e99034b5f7eb", "totalAmount": 99, "totalTax": 0.99 }, { "sellerId": "6360d4d5bd860240e258c582", "totalAmount": 11, "totalTax": 0.11 } ]
内容的提问来源于stack exchange,提问作者Stykgwar
相关产品推荐
相关产品推荐

