【问题标题】:MongoDB - Calculate $sum of values in array containing array elementsMongoDB - 计算包含数组元素的数组中的值的总和
【发布时间】:2021-02-22 03:55:01
【问题描述】:

我有一个聚合查询生成一个包含数组元素的数组。我怎样才能 $sum 这些值并产生类似于以下内容的输出:

  { "additionalReminders": 7 }

这是数据结构的一个例子。注意一些数组元素是空的,应该被忽略或计为0:

  {
    "additionalReminders": [
      [
        "1",
        "1"
      ],
      [],
      [],
      [
        "1"
      ],
      [],
      [
        "1"
      ],
      [],
      [
        "1"
      ],
      [],
      [
        "1"
      ],
      [],
      [],
      [
        "1"
      ]
    ]
  }

Mongo 游乐场: https://mongoplayground.net/p/BjSU_oYC8KG

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:

    这是您要查找的内容:

    db.collection.aggregate([
      {
        "$unwind": "$additionalReminders"
      },
      {
        "$unwind": "$additionalReminders"
      },
      {
        $group: {
          _id: null,
          "additionalReminders": {
            $sum: {
              "$toInt": "$additionalReminders"
            }
          }
        }
      },
      {
        $project: {
          _id: false,
          additionalReminders: true
        }
      }
    ])
    

    游乐场:https://mongoplayground.net/p/JInbHAmc_yV

    这个想法是展开你的领域几次以获得这个输出:

    ...
    {
        "_id": ObjectId("5a934e000102030405000000"),
        "additionalReminders": "1"
      },
      {
        "_id": ObjectId("5a934e000102030405000000"),
        "additionalReminders": "1"
      },
      {
        "_id": ObjectId("5a934e000102030405000000"),
        "additionalReminders": "1"
      },
    ...
    

    那么这只是对$additionalReminders 字段求和的简单问题,但不是在我们将其转换为 Int 之前。

    【讨论】:

      猜你喜欢
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 2020-09-17
      • 1970-01-01
      • 2012-05-08
      • 2014-05-02
      • 2017-07-15
      相关资源
      最近更新 更多