【问题标题】:MongoDB: Summing everything in a nested array [duplicate]MongoDB:对嵌套数组中的所有内容求和[重复]
【发布时间】:2020-11-01 12:21:29
【问题描述】:

我的数据库中有以下集合:

{
    "username" : "John",
    "shopping_cart" : {
        "coffee" : 2,
        "chocolate" : 3
      (...will have about 50 different products that can be added to the shopping cart)
    },
}

有没有一种方法可以汇总用户添加到购物车中的所有商品并获得购物车全部数量的总和?像这样的。

db.items.aggregate([
    {$group: {
        _id: null,
        prices: {$sum: "$all_items_in_shopping_cart}
    }}
])

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    您有 3 个不同的步骤

    1. 首先,将你的对象转换为数组

      $项目:{ 购物项目:{ $objectToArray: "$shopping_cart" } }

    2. 展开你的新元素

      $展开:{ 路径:“$shopingItems” }

    3. 根据id分组得到总和

      $组:{ _id: "$_id", 全部的: { $sum: "$shopingItems.v" }

    您的最终查询类似于:

    db. items. aggregate[
        {    
        '$project': {
          'shopingItems': {
            '$objectToArray': '$shopping_cart'
          }
        }
      }, {
        '$unwind': {
          'path': '$shopingItems'
        }
      }, {
        '$group': {
          '_id': '$_id', 
          'total': {
            '$sum': '$shopingItems.v'
          }
        }
      }
    ]

    【讨论】:

      【解决方案2】:

      你试试看,

      • $addFields 添加新字段 shopping_cart_sum
      • $reduce 到使用$objectsToArray 转换为数组后输入shopping_cart 数组,将initialValue 设置为零,以使用$add 添加对象键的值和initialValue 的值
      db.items.aggregate([
        {
          $addFields: {
            shopping_cart_sum: {
              $reduce: {
                input: { $objectToArray: "$shopping_cart" },
                initialValue: 0,
                in: { $add: ["$$this.v", "$$value"] }
              }
            }
          }
        }
      ])
      

      Playground

      【讨论】:

        猜你喜欢
        • 2015-06-20
        • 1970-01-01
        • 2021-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-25
        • 2017-01-13
        • 1970-01-01
        相关资源
        最近更新 更多