Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename nested keys in mongodb

I have a collection "user" as follows:

{
_id: "123",
"address": {
  "contact1":{
       "cell":"98765412345"
   },
  "contact2":{
       "cell":"98765412346"
   }
 }
}

I want to rename the field 'cell' to 'mobile' in all the nested objects contact1, contact2 and so on.

The following query works:

db.user.update({},{$rename:{'address.contact1.cell':'address.contact1.mobile'}})

I would ideally want all the nested objects to be updated. So I tried

db.user.update({},{$rename:{'address.$.cell':'address.$.mobile'}})

and this doesn't work. I searched for similar issues and all of them has nested arrays instead of maps (as in my case) and the answer that I got is that $rename doesn't work on nested arrays. I would want to know if its possible using a query instead of a script

like image 331
Meghashyam Sandeep V Avatar asked Sep 19 '25 21:09

Meghashyam Sandeep V


1 Answers

db.testuser.update({},{$rename:{'address.contact1.cell':'address.contact1.mobile'}}, false, true);

the false is for upsert:false and the true is for multi: true. You need the multi:true to update all your records. and offcourse you have to manually go through with each different key. This will update all the cell under contact1 object to mobile not the cell under contact2 object. Otherwise you have to write some scripts.

like image 86
Biswajit Panday Avatar answered Sep 22 '25 11:09

Biswajit Panday