1

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?

buydadip
  • 8,890
  • 22
  • 79
  • 154
Jase Whatson
  • 4,179
  • 5
  • 36
  • 45
  • what do you mean "per object"? Is it just one document you want to update, many (defined), or all? – Jinxcat Feb 13 '14 at 10:50

3 Answers3

9
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

Mustafa Genç
  • 2,569
  • 19
  • 34
2

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.

Community
  • 1
  • 1
Ewan
  • 14,592
  • 6
  • 48
  • 62
  • Thanks, I was able to do it with - db.User.find({name:/@/}).forEach(function (doc){ var email = doc.name; var name = doc.email; doc.email = email; doc.name = name; db.User.save(doc); }); – Jase Whatson Feb 13 '14 at 12:47
1

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