MongoDB关联多文档后对多层数组分组计数并求和价格
问题:MongoDB关联Order与Cart文档,按productCode统计数量和价格总和
文档结构
Order文档
[ { "_id": "62cdbae0421b250009acc329", "cartitems": "62cdbaaf74c9c80009f5a4b2" }, { "_id": "62d27e192b254600099ae680", "cartitems": "62d27d9d91568c0009866d23" } ]
Cart文档
[ { "_id": "62cdbaaf74c9c80009f5a4b2", "cartItems": [ { "productCode": ["NCK-1"], "Price": "56" }, { "productCode": ["NCK-2"], "Price": "56" } ] }, { "_id": "62d27d9d91568c0009866d23", "cartItems": [ { "productCode": ["NCK-3"], "Price": "56" }, { "productCode": ["NCK-1"], "Price": "56" } ] } ]
需求
将Order文档的cartitems字段与Cart文档的_id关联,按productCode分组,统计各productCode的出现数量并求和Price,期望结果:
- NCK-1:数量2,总价112
- NCK-2:数量1,总价56
- NCK-3:数量1,总价56
尝试的代码(未成功)
Order.aggregate([ { $lookup: { from: Cart.collection.name, localField: 'cartitems', foreignField: '_id', as: 'cartitems', }, }, { $unwind: '$cartitems' }, { $group: { _id: '$cartitems.cartItems.productCode', count: { $sum: '$cartitems.cartItems.Price' }, }, }, ]);
问题分析与修正方案
你的代码存在三个核心问题:
cartItems是数组,直接在$group中引用无法拆分单个商品项Price是字符串类型,直接$sum会导致计算错误productCode是单元素数组,需要提取出具体值作为分组依据
修正后的聚合管道如下:
Order.aggregate([ // 关联Cart文档 { $lookup: { from: Cart.collection.name, localField: 'cartitems', foreignField: '_id', as: 'cart' } }, // 展开关联得到的cart数组 { $unwind: '$cart' }, // 展开cart内的cartItems数组,拆分每个商品项 { $unwind: '$cart.cartItems' }, // 提取productCode数组的唯一值,同时将Price转为数字类型 { $addFields: { productCode: { $arrayElemAt: ['$cart.cartItems.productCode', 0] }, price: { $toDouble: '$cart.cartItems.Price' } } }, // 按productCode分组,统计数量和总价 { $group: { _id: '$productCode', count: { $sum: 1 }, totalPrice: { $sum: '$price' } } }, // 可选:格式化输出字段,让结果更直观 { $project: { _id: 0, productCode: '$_id', count: 1, totalPrice: 1 } } ]);
执行结果
[ { "productCode": "NCK-1", "count": 2, "totalPrice": 112 }, { "productCode": "NCK-2", "count": 1, "totalPrice": 56 }, { "productCode": "NCK-3", "count": 1, "totalPrice": 56 } ]
内容的提问来源于stack exchange,提问作者Life Smile
相关产品推荐
相关产品推荐

