set/unset the fields with another fields in mongo
Question :
How can I update a field with another field value in the same document (in both array & embedded sub documents)
From the attached JSON document, I would like to update ‘analyticUsers.geid’ to : ‘analyticUsers._id’ & tried all the below possible queries – but doesn’t work.
db.iainproposals.update(
{“_id” : 679}
, { $rename: {‘analyticUsers.geid’ : ‘analyticUsers._id’}})
db.iainproposals.update(
{“_id” : 679}
, { $set : { analyticUsers._id : analyticUsers.geid }})
db.iainproposals.update(
{“_id” : 679}
, { $unset : { analyticUsers.geid }})
db.iainproposals.update(
{“_id” : 679}
, { $set : { engagementManager._id : engagementManager.geid }})
Answer :
Unfortunately, the $rename option only works for single fields and embedded documents. The $rename option is not available for documents in an array.
There is however a way to update the fields in the array. You could do something like this:
db.iainproposals.find({"_id": 679}).forEach(function(item) |
{ |
for(i = 0; i != item.analyticUsers.length; ++i) |
{ |
item.analyticUsers[i]._id = item.analyticUsers[i].geid; |
delete item.analyticUsers[i].geid; |
} |
db.iainproposals.update({_id: item._id}, item); |
}); |
In essence, the sample above would iterate through each document that fits the find parameters and update each subdocument with the change. This would take a bit longer depending on how many documents you are trying to update, but it will updated your documents and change the field name for each document in the analyticUsers array.