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

Viewed 718

Is there an aggregation query available to convert the following: after unwind I plan to change the key based on the value inside each object and append it too has---(type)

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

to

{
    "hasaaa": {
        "type": "aaa",
        "values": [
            1,
            2,
            3
        ]
    },
    "hasbbb": {
        "type": "bbb",
        "values": [
            4,
            5,
            6
        ]
    }
}
1 Answers
  • $map to iterate loop of rows array
  • $concat to prepare the custom key string
  • return key-value from map
  • $arrayToObject convert key-value array to object
db.collection.aggregate([
  {
    $project: {
      rows: {
        $arrayToObject: {
          $map: {
            input: "$rows",
            in: {
              k: { $concat: ["has", "$$this.type"] },
              v: "$$this"
            }
          }
        }
      }
    }
  }
])

Playground

Related