2017  Kodetalk | Feedback | Privacy Policy | Terms | About

Update MongoDB field using value of another field

In MongoDB, is it possible to update the value of a field using the value from another field? The equivalent SQL would be something like:

UPDATE Person SET Name = FirstName + " " + LastName

And the MongoDB pseudo-code would be:

db.person.update( {}, { $set : { name : firstName + " " + lastName } );


According to a (now unavailable) comment on the Update documentation page, you cannot reference the current document's properties from within an update().

You'll have to iterate through all the documents and update them like this:


function (e) {    

// update document, using its own properties    

e.coords = { lat: e.lat, lon: e.lon };    

// remove old properties    

delete e.lat;    

delete e.lon;    

 // save the updated document    

db.events.save(e);   } ) 

Such a function can also be used in a map-reduce job or a server-side db.eval() job, depending on your needs.


You can run server-side code with db.eval().
db.eval(function() {    

db.collection.find({tag : "refurb"}).forEach(function(e) {       

        e.Price = e.Price * 0.5;       




Note this will block the DB, so it's better to do find-update operation pair.
See http://www.mongodb.org/display/DOCS/Server-side+Code+Execution

Answer is