Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update key in nested document

Tags:

mongodb

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
        }
    }
}
like image 484
Jahroots Avatar asked May 02 '26 11:05

Jahroots


2 Answers

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

like image 150
turivishal Avatar answered May 05 '26 08:05

turivishal


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

like image 34
J.F. Avatar answered May 05 '26 08:05

J.F.