I have accidentally inserted the email and name columns around the wrong way
{
"_id" : ObjectId("52e72d00d1c3f81199000002"),
"email" : "John",
"name" : "john@gmail.com"
}
How can I fix this on a per ObjectId
basis?
I have accidentally inserted the email and name columns around the wrong way
{
"_id" : ObjectId("52e72d00d1c3f81199000002"),
"email" : "John",
"name" : "john@gmail.com"
}
How can I fix this on a per ObjectId
basis?
db.collection.update( { condition }, { $rename: { "email": "name" } } )
Don't forget change name
field to something like name_tmp
before this operation. Then rename name_tmp
into email
Documentation here
Have a look at this question how can i update field with another field's value.
It is tough to do in a single update query but you can use a javascript forEach
loop:
db.item.find(conditions...).forEach( function (doc) {
var email = doc.name;
var name = doc.email
doc.email = email;
doc.name = name
db.item.save(doc);
});
You could maybe look at doing this in a one-liner like this;
doc.email = [doc.name, doc.name = doc.email][0];
But this is untested.
Thanks it works for me but I have had to set the option 'multi' to true.
db.collection('collection').update({ condition }, { $rename: { "currentName": "newName" } }, { multi: true });