1

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.

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
Oudadham
  • 23
  • 4

1 Answers1

1

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

Yong Shun
  • 35,286
  • 4
  • 24
  • 46