Update field with another field's value in the document

firefox01 picture firefox01 · Apr 9, 2010 · Viewed 30.5k times · Source

I have a collection t1 with the following fields in its schema

_id, field1, field1

I want set field2's value field1 like sql:

update t1 set field1=field2;

How do I do it in MongoDB?

Answer

Jakub P. picture Jakub P. · Nov 23, 2010

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...).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)