将MongoDB中的嵌套数组分组为单个数组。

huangapple go评论67阅读模式
英文:

Group nested array to single array in mongodb

问题

以下是翻译好的部分:

我有一个聚合结果(包含两个对象的数组),如下所示:

[
  {
    "immunizationDetails": [
      [
        "Rubella"
      ],
      [
        "PCV13",
        "Tdap"
      ]
    }
  },
  {
    "immunizationDetails": [
      [
        "Hepatitis B",
        "HIB"
      ],
      [
        "PCV13"
      ]
    }
  }
]
但我需要将 immunizationDetails 放入一个单一数组中,如下所示:

[
  {
    "immunizationDetails": ["Rubella", "PCV13", "Tdap"]
  },
  {
    "immunizationDetails": ["Hepatitis B", "HIB", "PCV13"]
  }
]

需要有人的宝贵帮助。
英文:

I am having an aggregation result (an array of two objects) like this:

[
  {
    "immunizationDetails": [
      [
        "Rubella"
      ],
      [
        "PCV13",
        "Tdap"
      ]
    ]
  },
  {
    "immunizationDetails": [
      [
        "Hepatitis B",
        "HIB"
      ],
      [
        "PCV13"
      ]
    ]
  }
]

But I need immunizationDetails to be in a single array like this:

[
  {
    "immunizationDetails": ["Rubella", "PCV13", "Tdap"] 
  },
  {
    "immunizationDetails": ["Hepatitis B", "HIB", "PCV13"]
  }
]

Need someone's valuable help.

答案1

得分: 1

只需添加一个$reduce$concatArrays 以展平结果。

db.collection.aggregate([
  {
    "$set": {
      "immunizationDetails": {
        "$reduce": {
          "input": "$immunizationDetails",
          "initialValue": [],
          "in": {
            "$concatArrays": [
              "$$value",
              "$$this"
            ]
          }
        }
      }
    }
  }
])

Mongo Playground

英文:

Just add one more $reduce with $concatArrays to flatten the result.

db.collection.aggregate([
  {
    "$set": {
      "immunizationDetails": {
        "$reduce": {
          "input": "$immunizationDetails",
          "initialValue": [],
          "in": {
            "$concatArrays": [
              "$$value",
              "$$this"
            ]
          }
        }
      }
    }
  }
])

Mongo Playground

huangapple
  • 本文由 发表于 2023年2月24日 02:02:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548635.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定