猫鼬加法/苏明子文档数组值,位于另一个子文档数组中



我的文档看起来像这样:

_id:'111'
products:[
{
_id:'pqr'
nums:[
{_id:'aaa',
quantity:30
},
{_id:'bbb',
quantity:40
}
]
}
]

我需要得到:

(i( 数量字段的总和,该字段位于 NUMS 子文档中,该字段再次位于产品子文档中。

(ii( 要作为一个整体返回的产品数组(其中包含计算的数量和 nums 子文档(

以下是我希望我的输出是这样的:

products:[
{
_id: 'pqr',
nums:[
{_id:'aaa',
quantity:30
},
{_id:'bbb',
quantity:40
}
],
quantity: 70
}
]

到目前为止,我已经尝试这样做

Shop.aggregate([
{$match: {'_id':'111'},
{$unwind: "$products"},
{$group:{
_id : "$_id",
nums:{$last:"$nums"},
quatity: //I have no idea how to get this total quantity which corresponds to _id:'pqr'
}
}
])

关于如何做到这一点的任何解决方法?

这是一个很好的用例$reduce

Shop.aggregate([
{$match: {'_id':'111'},
{$unwind: "$products"},
{$addFields:{
"products.quantity":{
$reduce:{
input: "$products.nums",
initialValue: 0
in: {$sum:["$$value","$$this.quantity"]}
}
}
}}
])

最新更新