Update field with another field’s value in the document [duplicate]

Good and bad news here.

Bad news is that AFAIK you can’t do it with a single update() call – mongo doesn’t support referring to current object in update.

Good news is that there are other ways to do it, e.g. you can run a forEach loop:

db.item.find(conditions...).snapshot().forEach( function (doc) {
  doc.field1 = doc.field2; 
  db.item.save(doc); 
});

You can run forEach in the admin shell (‘mongo’ command), or through some of the methods of your specific driver (e.g. in PHP I’d expect it to work with mongodb.execute() as described in here: http://www.php.net/manual/en/mongodb.execute.php)

Leave a Comment