MongoDB聚合中如何为$lookup关联数组添加$add计算的Total字段
解决MongoDB聚合中关联数组字段求和的问题
嘿,我明白你遇到的问题了——因为$lookup返回的Matches是一个数组,直接在$project里用$add肯定行不通,得先处理数组里的每一个元素才行。别担心,有两种方法可以实现你想要的效果,我先给你推荐最简洁高效的那种:
方法一:用$map直接处理数组元素
这种方法不需要拆分数组,直接在Matches数组内部对每个元素计算Total字段,性能更好,代码也更简洁。修改你的聚合查询如下:
gameresult = db.products.aggregate([ {'$match': {'Platform': variable}}, {'$lookup': { 'from': 'vendorgames', 'localField': 'Product', 'foreignField': 'Product', 'as': 'Matches' }}, {'$project': { '_id': 0, 'Product': '$Product', 'Price': '$Price', 'Matches': { '$map': { 'input': '$Matches', 'as': 'match', 'in': { 'ShippingCharge': '$$match.ShippingCharge', 'PreownedPrice': '$$match.PreownedPrice', 'Total': {'$add': ['$$match.ShippingCharge', '$$match.PreownedPrice']} } } } }} ])
代码解释:
$map会遍历Matches数组里的每一个元素(用$$match指代当前元素)- 在
in字段里,我们保留原有的ShippingCharge和PreownedPrice,同时新增Total字段,用$add把两个数值相加 - 最后输出的
Matches数组里,每个元素都会带上计算好的Total
执行这个查询后,你得到的结果就会和你期望的完全一致:
{u'Matches': [{u'ShippingCharge': 200, u'PreownedPrice': 2000, u'Total': 2200 }], u'Product': u'A Way Out', u'Price': u'2,499.00'}
方法二:用$unwind拆分数组后处理(适合复杂场景)
如果你的Matches数组里有多个元素,或者需要做更多复杂的处理,也可以用$unwind先把数组拆分成单个文档,计算Total后再重新组合:
gameresult = db.products.aggregate([ {'$match': {'Platform': variable}}, {'$lookup': { 'from': 'vendorgames', 'localField': 'Product', 'foreignField': 'Product', 'as': 'Matches' }}, {'$unwind': '$Matches'}, // 拆分Matches数组 {'$addFields': { 'Matches.Total': {'$add': ['$Matches.ShippingCharge', '$Matches.PreownedPrice']} }}, {'$group': { // 重新组合回原结构 '_id': '$_id', 'Product': {'$first': '$Product'}, 'Price': {'$first': '$Price'}, 'Matches': {'$push': '$Matches'} }}, {'$project': { // 去掉_id字段 '_id': 0, 'Product': 1, 'Price': 1, 'Matches': 1 }} ])
这个方法虽然步骤多一点,但灵活性更强,适合数组元素较多或者需要额外处理的场景。
内容的提问来源于stack exchange,提问作者fear_matrix
相关产品推荐
相关产品推荐

