【问题标题】:MongoDB aggregate & lookup between 3 collectionsMongoDB 在 3 个集合之间聚合和查找
【发布时间】:2020-08-25 23:24:53
【问题描述】:

我正在尝试创建一个简单的客户/产品/订单数据库。 This is the customer collection

This is the order collection

This is the product collection

我更喜欢使用 ref 键而不是嵌入文档只是为了锻炼。 我正在尝试按客户名称进行分组,然后为每个客户求和他的总订单数 = Sum (Product_price x Quantity)。

这是我尝试过的查询,但它不起作用:/

db.customers.aggregate([
  {$lookup:{from:"orders", localField:"ordered",foreignField:"_id", as:"Bought"}},
  {$lookup:{from:"products", localField:"Bought.Includes.product",foreignField:"_id", as:"User_products"}},
  {$group:{_id:{name:"$name"},total: { $multiply: [ "$price", "$quantity" ] }}},
  {$project: {name:1, total:1}  }
]).pretty()

【问题讨论】:

  • 您为订单和产品发布了相同的图片
  • 没问题,欢迎来到 Stack Overflow。另一个提示:请避免发布数据图像,而是将数据作为文本发布在问题内容中。您可以使用编辑器格式化功能使其更具可读性。请参阅此处的指南以了解如何询问stackoverflow.com/help/how-to-ask

标签: mongodb nosql


【解决方案1】:

你几乎明白了,只是一些问题。代码注释中的解释

[
  {
    $lookup: {
      from: "orders",
      localField: "ordered",
      foreignField: "_id",
      as: "Bought"
    }
  },
  {
    $unwind: '$Bought' //  You have to use $unwind on an array if you want to use a field in the subdocument array to further usage with `$lookup` 
  },
  {
    $unwind: '$Bought.Includes' // Also $unwind here
  },
  {
    $lookup: {
      from: "products",
      localField: "Bought.Includes.product",
      foreignField: "_id",
      as: "User_products"
    }
  },
  {
    $unwind: '$User_products' // also $unwind here
  },
  {
    $group: {
      _id: "$name" , // [optional] only one field to use as key, no need to wrap in an object
      total: {
        $sum: { // don't forget to $sum here
          $multiply: [
            "$User_products.Price", // access the value with the full object path
            "$Bought.Includes.quantity" // access the value with the full object
          ]
        } 
      }
    }
  },
]

更多关于$unwind

提示:确保大写/小写的用法一致,我注意到你使用product vs Price vs Quantity 会更容易出现拼写错误

【讨论】:

  • 是的,我总是忘记上/下嘿嘿。由于某种原因,我现在收到此错误imgur.com/a/FW8e5gN
  • 忘了 $unwind 另一个阶段,我已经修改了答案以包含修复
  • 谢谢哥们,辛苦了!我有一个问题:我来自 SQL 并且是 mongoDB 的新手——我创建集合的方式是否正确?像我一样使用 ref 键是正确的还是有更好的方法?因为像你刚才那样“加入”可能是地狱,我想知道是否有更好的方法来创建集合以更好地查询
  • 在 NoSQL 世界中,设计模式的方法大多有多种。大多数情况下,这将取决于您的数据的访问模式,即您如何查询它。您可以从以下指南开始:1.docs.mongodb.com/manual/core/data-model-design 2.mongodb.com/blog/post/…
猜你喜欢
  • 2020-02-16
  • 2020-08-31
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 2019-03-17
  • 1970-01-01
  • 2018-03-06
相关资源
最近更新 更多