【问题标题】:Regroup all elements of nested array of nested array into a single array将嵌套数组的嵌套数组的所有元素重新组合成一个数组
【发布时间】:2021-10-01 10:34:24
【问题描述】:

我有这个收藏:

{
  "_id": ObjectId("6045eec8f113547ddd3472d9"),
  "execution": {
    "_id": ObjectId("6045eec8f113547ddd3472d8"),
    "steps": [
      {
        "_id": ObjectId("6045eec8f113547ddd3472d7"),
        "actions": [
          {
            "_id": ObjectId("6045eec8f113547ddd3472d6"),
            "title": "action title"
          }
        ]
      }
    ]
  }
}

我想达到这个结果:

{
  "_id": ObjectId("6045eec8f113547ddd3472d9"),
  "allActions": [
    {
      "_id": ObjectId("6045eec8f113547ddd3472d6"),
      "title": "action title"
    }
  ]
}

为了澄清更多,我想添加一个数组,将“步骤”数组下的所有“动作”组合在一起

db.getCollection("missions").aggregate([
    {
        $match: {
            _id: ObjectId("6045eec8f113547ddd3472d9")
        }
    },
    {
        $addFields: {
            "allActions": "$execution.steps"
        }
    }
])

有人可以帮我完成代码部分,让我获得所需的输出吗?

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您可以只使用$reduce 和$concatArrays 对actions 数组中的所有条目进行分组

    db.missions.aggregate([
      {
        $match: {
          _id: ObjectId("6045eec8f113547ddd3472d9")
        }
      },
      {
        $addFields: {
          "allActions": {
            "$reduce": {
              "input": "$execution.steps.actions",
              "initialValue": [],
              "in": {
                "$concatArrays": [
                  "$$value",
                  "$$this"
                ]
              }
            }
          }
        }
      }
    ])
    

    这是Mongo playground 供您参考。

    【讨论】:

    • 成功了,谢谢你
    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多