【问题标题】:MongoDB lookup and unwind not giving correct resultsMongoDB 查找和展开没有给出正确的结果
【发布时间】: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


    【解决方案1】:

    首先,您使用 "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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2019-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多