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

141
Views
Update key in nested document

I would like to update the keys of the object "values" in the following document stored in a MongoDB collection:

{
    "data": {
        "name": "Doe",
        "values": {
            "AA_Avg": 13,
            "BB_Avg": 19,
            "CC_Avg": 18
        }
    }
}

To make it looks like this:

{
    "data": {
        "name": "Doe",
        "values": {
            "AA_MT": 13,
            "BB_MT": 19,
            "CC_MT": 18
        }
    }
}
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Dynamic update you can use update with aggregation pipeline starting from MongoDB 4.2,

First approach: using $rpelaceOne,

  • $objectToArray convert data.values from object to array in k and v format
  • $map to iterate loop of above converted array
  • $replaceOne will replace string on the base of input and replacement
  • $arrayToObject back to convert from array to object
db.collection.update({},
  [{
    $set: {
      "data.values": {
        $arrayToObject: {
          $map: {
            input: { $objectToArray: "$data.values" },
            in: {
              k: {
                $replaceOne: {
                  input: "$$this.k",
                  find: "Avg",
                  replacement: "MT"
                }
              },
              v: "$$this.v"
            }
          }
        }
      }
    }
  }
])

Playground


Second approach: using $split, $arrayElemAt, $concat,

Playground

over 4 years ago · Santiago Trujillo Report

0

You can use $rename function like this:

Is simply, you only have to say what field do you want to update and the new value.

Note that due to nested objects you have to use dot notation as explained into docs

MongoDB uses the dot notation to access the elements of an array and to access the fields of an embedded document.

db.collection.update({},
{
  "$rename": {
    "data.values.AA_Avg": "data.values.AA_MT",
    "data.values.CC_Avg": "data.values.BB_MT",
    "data.values.DD_Avg": "data.values.CC_MT"
  }
})

Example here

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!