MongoDB 聚合以根据每个对象中的值更改键

MongoDB aggregation to change the key based on value in each object

是否有聚合查询可用于转换以下内容: 展开后,我计划根据每个对象内的值更改密钥并将其附加到 has---(type)

{
    "rows": [
        {
            "type": "aaa",
            "values": [
                1,
                2,
                3
            ]
        },
        {
            "type": "bbb",
            "values": [
                4,
                5,
                6
            ]
        }
    ]
}

{
    "hasaaa": {
        "type": "aaa",
        "values": [
            1,
            2,
            3
        ]
    },
    "hasbbb": {
        "type": "bbb",
        "values": [
            4,
            5,
            6
        ]
    }
}
  • $map 迭代 rows 数组
  • 的循环
  • $concat准备自定义密钥字符串
  • return 来自地图的键值
  • $arrayToObject 将键值数组转换为对象
db.collection.aggregate([
  {
    $project: {
      rows: {
        $arrayToObject: {
          $map: {
            input: "$rows",
            in: {
              k: { $concat: ["has", "$$this.type"] },
              v: "$$this"
            }
          }
        }
      }
    }
  }
])

Playground