【发布时间】:2020-02-06 12:29:14
【问题描述】:
我有包含不同卖家所有产品列表的产品模型和包含订购产品列表的订单模型
我需要查询,获取卖家的总收入
产品型号:
{
"_id": 1,
"ProductName": "product 1",
"Price": 100,
"SellerId": 1
},
{
"_id": 2,
"ProductName": "product 2",
"Price": 200,
"SellerId": 2
},
{
"_id": 3,
"ProductName": "product 3",
"Price": 50,
"SellerId": 1
}
订单模型:
{
"_id": 1,
"ProductId": 1,
"Price": 100,
"Quantity": 2,
"Total": 200,
"Status": true
},
{
"_id": 2,
"ProductId": 2,
"Price": 200,
"Quantity": 10,
"Total": 2000,
"Status": true
}
聚合
db.products.aggregate([
{
"$match": { "SellerId" :1 }
},
{
$lookup: {
from: 'orders',
localField: '_id',
foreignField: 'ProductId',
as: 'requests.service'
}
},
$group:{
_id: "$_id",
totalAmount: { $sum: "$Total" },
}
])
搜索特定卖家时,最终输出显示为 0,无法找出解决方案。
卖家 1 的预期输出为 200,卖家 2 的预期输出为 2000
【问题讨论】:
标签: node.js mongodb mongoose mongodb-query mongodb-atlas