【发布时间】:2020-09-17 14:44:30
【问题描述】:
我的文档如下所示:
_id:'111'
products:[
{
_id:'pqr'
nums:[
{_id:'aaa',
quantity:30
},
{_id:'bbb',
quantity:40
}
]
}
]
我需要得到:
(i) nums 子文档中的数量字段的总和,该子文档又在 products 子文档中。
(ii) 要作为一个整体返回的 products 数组(其中包含计算的数量和 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'
}
}
])
关于如何做到这一点的任何解决方法?
【问题讨论】:
标签: mongodb mongoose aggregation-framework