Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MongoDB self-referenced values in query

Is it possible to get a self-referenced value in an update query in MongoDB? In MySQL, you can run:

UPDATE table SET column1 = column2 + column3,...

From what I know, only MapReduce can be used to do this while server-side in MongoDB. How do I use MapReduce to do this?

like image 469
enderskill Avatar asked Mar 07 '26 11:03

enderskill


1 Answers

Is it possible to get a self-referenced value in an update query in MongoDB?

No, this update is not possible with the normal querying/updating system.

From what I know, only MapReduce can be used to do this while server-side in MongoDB.

Map / Reduce is used to summarize existing data and output that data to a separate collection/table. Map / Reduce is not intended to update existing data.

To run this update with MongoDB you will need to run a simple for loop over the entire collection, updating each one. You can do this from any of the drivers including the shell.

db.table.find().forEach( function(x) {
  var newValue = x.column2 + x.column3; // Add column2 & 3
  db.table.update({_id: x._id}, { $set: { column1: newValue } }); // Set the value on column1
} )
like image 98
Gates VP Avatar answered Mar 10 '26 06:03

Gates VP