首页 > 解决方案 > 如何在 Mongo DB 中合并数组和文档字段

问题描述

我在 MongoDB 中有这个文档

[
    {
        "locations": [5, 5],
        "id": "fff"
    },
    {
        "locations": [7, 7],
        "id": "aaa"
    },
    {
        "locations": [9, 9],
        "id": "ccc"
    }
]

我想将数组字段和字符串字段合并为一个包含它们组合的字段,如下所示

{
    "device": [
        ["fff", 5, 5],
        ["aaa", 7, 7],
        ["ccc", 9, 9]
    ]
}

是否可以通过聚合来做到这一点?谢谢你。

标签: mongodbmongodb-queryaggregation-framework

解决方案


您可以使用$concatArrays合并两个字段,然后$group使其成为二维数组

db.collection.aggregate([
  { "$group": {
    "_id": null,
    "devices": { "$push": { "$concatArrays": [["$id"], "$locations"] } }
  }}
])

输出

[
  {
    "devices": [
      ["fff", 5, 5],
      ["aaa", 7, 7],
      ["ccc", 9, 9]
    ]
  }
]

推荐阅读