Jahroots
Jahroots

Reputation: 121

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
        }
    }
}

Upvotes: 3

Views: 527

Answers (2)

turivishal
turivishal

Reputation: 36094

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

Upvotes: 4

J.F.
J.F.

Reputation: 15177

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

Upvotes: 2

Related Questions