Rename/Update JSON field keys in Mongo Document: In this tutorial will see how to modify/rename JSON keys without deleting/Modifying the JSON Object for the respective key.

I have a document shown below

{
  "_id" : ObjectId("5b594b462fe5553ce8071c27"),
  "grades" : [80.0, 200, 300],
  "json1" : {
    "key1" : "value1",
    "key2" : "value2"
  },
  "json2" : {
    "key2" : "value",
    "key1" : "value1"
  }
}

Now I want to update the key “key1” to “key” in “json1” object without delete or re-adding the document.

with the help of dotted notation, we are telling MongoDB to update a particular node with the specific key should be updated or modified with the name we want. below is the Query

db.dummy_collection.update(
   {},
   {$rename: { 'json1.key1': 'json1.key'} },
{  multi: true} 
);

From the above Query, we are mentioning the object in “json1” with key “key1” needs to be renamed with “key” by using dot notation.

in the Query we have mentioned multi:true we are telling MongoDB to update multiple records which are matching with the same pattern “json1.key1” from all documents

After executing the Query, below is the output.

{
  "_id" : ObjectId("5b594b462fe5553ce8071c27"),
  "grades" : [80.0, 200, 300],
  "json1" : {
    "key2" : "value2",
    "key" : "value1"
  },
  "json2" : {
    "key2" : "value",
    "key1" : "value1"
  }
}

Also Read: Update Arrays Element in MongoDB

Rename/Update JSON field keys in Mongo Document

Leave a Reply

Your email address will not be published. Required fields are marked *