Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
How to modify the "key" element in MongoDB 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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!