MongoDB 查找和展开没有给出正确的结果

MongoDB lookup and unwind not giving correct results

我有包含不同卖家所有产品列表的产品模型和包含订购产品列表的订单模型

我要查询,获取卖家赚取的总金额

产品型号:

{
  "_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

首先,您使用 "SellerId" :1 进行过滤。这是不正确的。

其次你需要放松一下requests.service。 对于 $unwind 聚合,您可以在此处找到信息:

https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/

您的查询必须是这样的:

db.products.aggregate([
  {
    $lookup: {
      from: "orders",
      localField: "_id",
      foreignField: "ProductId",
      as: "requests.service"
    }
  },
  {
    $unwind: "$requests.service"
  },
  {
    $group: {
      _id: "$_id",
      totalAmount: {
        $sum: "$requests.service.Total"
      }
    }
  },
  {
    $sort: {
      "totalAmount": 1
    }
  }
])

https://mongoplayground.net/p/t4MfjgcyxXx

$lookup 运算符产生一个数组字段,您需要在 $group 管道之前 $unwind 新字段以获得所需的结果。 $unwind解构数组字段。所以 {$unwind: "$requests.service"} 请注意 $requests.service 前面的美元符号 ($),然后你的小组将完成工作