【问题标题】:Reduce an array of elements into an object in MongoDB将元素数组缩减为 MongoDB 中的对象
【发布时间】:2023-02-07 16:36:17
【问题描述】:

我有一个名为 Venue 的 MongoDB 集合,其元素类型为:

{
    venue: "Grand Hall",
    sections: [{
        name: "Lobby",
        drinks: [{
            name: "Vodka",
            quantity: 3
        }, {
            name: "Red Wine",
            quantity: 1
        }]
    }, {
        name: "Ballroom",
        drinks: [{
            name: "Vodka",
            quantity: 22
        }, {
            name: "Red Wine",
            quantity: 50
        }]
    }]
}

我想计算聚会中每种饮料的总量。所以我希望我的结果是这样的:

{
    venue: "Grand Hall",
    sections: 2,
    drinks: [{
        name: "Vodka",
        quantity: 25
    }, {
        name: "Red Wine",
        quantity: 51
    }]
}

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:
    1. $unwind - 将sections 数组解构为多个文档。

    2. $unwind - 将sections.drinks 数组解构为多个文档。

    3. $group - 按venuesections.drinks.name 分组。对quantity 进行求和。

    4. $group - 按venue 分组。对上一阶段的分组结果进行计数。并将文档添加到drinks 数组中。

      db.collection.aggregate([
        {
          $unwind: "$sections"
        },
        {
          $unwind: "$sections.drinks"
        },
        {
          $group: {
            _id: {
              venue: "$venue",
              drink_name: "$sections.drinks.name"
            },
            quantity: {
              $sum: "$sections.drinks.quantity"
            }
          }
        },
        {
          $group: {
            _id: "$venue",
            section: {
              $sum: 1
            },
            drinks: {
              $push: {
                name: "$_id.drink_name",
                quantity: "$quantity"
              }
            }
          }
        }
      ])
      

      Demo @ Mongo Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-16
      • 2012-01-17
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 2016-09-23
      • 1970-01-01
      相关资源
      最近更新 更多