MongoDB - 如何聚合每条记录的数据

MongoDB - How to aggregate data for each record

我有一些这样的存储数据:

{
    "_id" : 1,
    "serverAddresses" : {
        "name" : "0.0.0.0:8000",
        "name2": "0.0.0.0:8001"
    }
}

我需要汇总数据:

[
  {
    "gameId": "1",
    "name": "name1",
    "url": "0.0.0.0:8000"
  },
  {
    "gameId": "1",
    "name": "name2",
    "url": "0.0.0.0:8001"
  }
]

不使用for循环的解决方案是什么?

  1. $project - 通过将 $serverAddress 转换为(键值)数组来添加 addresses 字段。
  2. $unwind - 将 addresses 字段解构为多个文档。
  3. $replaceRoot - 根据(2)修饰输出文档。
db.collection.aggregate([
  {
    "$project": {
      "addresses": {
        "$objectToArray": "$serverAddresses"
      }
    }
  },
  {
    $unwind: "$addresses"
  },
  {
    "$replaceRoot": {
      "newRoot": {
        gameId: "$_id",
        name: "$addresses.k",
        address: "$addresses.v"
      }
    }
  }
])

Sample Mongo Playground