在mongodb中将嵌套数组分组为单个数组

wztqucjr  于 2023-03-01  发布在  Go
关注(0)|答案(1)|浏览(131)

我得到的聚合结果(两个对象的数组)如下所示:

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

但我需要immunizationDetails位于单个数组中,如下所示:

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

需要某人有价值的帮助。

wgeznvg7

wgeznvg71#

只需将$reduce$concatArrays再相加一个即可使结果变平。

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

Mongo Playground

相关问题