Search code examples
arraysmongodbmongodb-queryrenamemongodb-update

MongoDB - How to modify the "key" element in the document


I am having the below document structure:

[
  {
    "network_type": "ex",
    "rack": [
      {
        "xxxx": {
          "asn": 111111,
          "nodes": {
            "business": [
              "sk550abcc1eb01.abc.com",
              "sk550abcc1eb10.abc.com",
              "sk550abcc1eb19.abc.com",
              "sk550abcc1eb28.abc.com"
            ]
          },
          "region": "ex-01",
          "zone": "01a"
        }
      }
    ]
  }
]

I need to rename/update the key array element "xxxx" to "details".

I tried the below command, but it doesn't seem to work.

db.collection.update({},
{
  $rename: {
    "rack.xxxx": "details"
  }
})

Link: https://mongoplayground.net/p/9dcDP-VKZ55

Please help me.


Solution

  • You can't direct $rename the field name which is within the array.

    Instead,

    1. Iterate with document(s) in the rank array, create the details field with the value of xxxx and next append this field to each document.

    2. Remove the path with $rank.xxxx to remove the xxxx field from the document(s) in the rank array.

    db.collection.update({},
    [
      {
        $set: {
          rack: {
            $map: {
              input: "$rack",
              in: {
                $mergeObjects: [
                  {
                    "details": "$$this.xxxx"
                  },
                  "$$this"
                ]
              }
            }
          }
        }
      },
      {
        $unset: "rack.xxxx"
      }
    ])
    

    Sample Mongo Playground