我有两个收藏品
1.Product collection ==>
/* 1 */
{
"_id" : 154,
"name" : "Chocolate Heaven",
"price" : 7
}
/* 2 */
{
"_id" : 155,
"name" : "Tasty Lemons",
"price" : 8
}
/* 3 */
{
"_id" : 156,
"name" : "Vanilla Dreams",
"price" : 9
}
2.订单收集==>
/* 1 */
{
"_id" : 1,
"product_id" : 154,
"quantity" : 10
}
/* 2 */
{
"_id" : 2,
"product_id" : 155,
"quantity" : 3
}
/* 3 */
{
"_id" : 3,
"product_id" : 156,
"quantity" : 6
}
/* 4 */
{
"_id" : 4,
"product_id" : 154,
"quantity" : 1
}
我期待产品的出货量是使用mongodb的总价格
156 Vanilla Dreams 9 6 54
db.getCollection('order').aggregate([
{$group : {_id :{ product_id : "$product_id"}, sellCount : { $sum : "$quantity"}}},
{$lookup : { from : 'product',localField : '_id.product_id' , foreignField :'_id',as: 'prodDetails' }},
{$match: {prodDetails: {$ne: []}}}
]);
答案 0 :(得分:0)
您可以尝试运行仅使用两个步骤 $lookup
和 $addFields
的管道,如下所示:
db.product.aggregate([
{
"$lookup": {
"from": "order",
"localField": "_id",
"foreignField": "product_id",
"as": "orders"
}
},
{
"$addFields": {
"total": {
"$multiply": [
"$price",
{ "$sum": "$orders.quantity" }
]
}
}
}
])