【问题标题】:How to build aggregation pipeline to receive data in this certain way?如何构建聚合管道以这种方式接收数据?
【发布时间】:2021-04-14 19:45:20
【问题描述】:

我有一个如下所示的 MongoDB 集合:

const data = [
  { name: "eggplant", price: 3.42, quantity: 1},
  { name: "eggplant", price: 3.17, quantity: 3},
  { name: "potato", price: 2.12, quantity: 5},
  { name: "potato", price: 1.99, quantity: 10},
  { name: "eggplant", price: 3.33, quantity: 3},
  { name: "cucumber", price: 5.02, quantity: 4},
  { name: "lettuce", price: 3.42, quantity: 1.5},
  { name: "cucumber", price: 4.45, quantity: 4},
]

我想在我的服务器上使用聚合框架过滤这些数据,按名称接收一个文档,并计算其他字段。 基本上我需要计算每个特定项目的平均价格和总数量。 所以我需要以某种方式总结每个特定项目的价格,将其除以具有该名称的文档数量并将其设置为新字段,并获取数量的总和。 所以我想在我的输出中有这样的数据:

[
  { name: "eggplant", averagePrice: 3.30, quantitySum: 7},
  { name: "potato", averagePrice: 2.05, quantitySum: 15},
  { name: "cucumber", averagePrice: 4.73, quantitySum: 8},
  { name: "lettuce", averagePrice: 3.42, quantity: 1.5},
]

我的问题是,聚合框架中是否有任何特殊的运算符可以帮助我轻松地解决这个问题并且我可以深入研究?甚至可以在聚合框架中进行这样的计算吗?

【问题讨论】:

    标签: javascript mongodb mongodb-query aggregation-framework


    【解决方案1】:

    演示 - https://mongoplayground.net/p/GtvyGysBNM6

    使用$group

    按指定的 _id 表达式对输入文档进行分组,并为每个不同的分组输出一个文档。每个输出文档的 _id 字段包含唯一的分组值。

    $avg

    $sum

    db.collection.aggregate([
        $group: {
          _id: "$name", // group by name
          averagePrice: { $avg: "$price" },
          quantitySum: { $sum: "$quantity" }
        }
      }
    ])
    

    如果你想获取 name 而不是 _id 添加$project

    演示 - https://mongoplayground.net/p/bSfdYgg9lUo

    {
        $project: {
          _id: 0,
          name: "$_id",
          averagePrice: 1,
          quantitySum: 1,
          
        }
      }
    

    【讨论】:

    • 就这么简单吗?我一直在寻找一些疯狂复杂的东西。非常感谢您的这一课。
    • @BlackH3art 在你知道之前它很复杂,现在你知道了。所以对你来说很简单:)
    猜你喜欢
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 2020-12-12
    • 2016-05-07
    • 2020-10-03
    • 1970-01-01
    相关资源
    最近更新 更多