I just came across this looking for the equivalent of MongoDB SQL code as follows:
update t set c1 = c2 where ...
Sergio is correct that you cannot refer to another property as a value in a direct update. However, db.c.find(...) returns a cursor, and this cursor has a forEach method :
Queries on MongoDB return a cursor that can be repeated to retrieve the results. The exact request method depends on the language driver. The details below focus on MongoDB shell requests (i.e. mongo ).
The find() shell method returns a cursor object, which you can then iterate over to extract specific documents from the result. We use hasNext() and next() for this purpose.
for( var c = db.parts.find(); c.hasNext(); ) { print( c.next()); }
In addition, in the forEach() shell it can be used with a cursor:
db.users.find().forEach( function(u) { print("user: " + u.name); } );
So you can say the following:
db.QUESTIONS.find({}, {_id: true, i_up: true, i_down: true}).forEach(function(q) { db.QUESTIONS.update( { _id: q._id }, { $set: { i_pp: q.i_up * 100 - q.i_down * 20 } } ); });
to update them one at a time without leaving MongoDB.
If you are using a driver to connect to MongoDB, then there must be some way to send a JavaScript string to MongoDB; for example with a Ruby driver that you would use eval :
connection.eval(%q{ db.QUESTIONS.find({}, {_id: true, i_up: true, i_down: true}).forEach(function(q) { db.QUESTIONS.update( { _id: q._id }, { $set: { i_pp: q.i_up * 100 - q.i_down * 20 } } ); }); })
Other languages should be similar.