2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

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 } );

userimage

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:

db.events.find().snapshot().forEach(  

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.

userimage

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;       

        db.collection.save(e);   

    });

});

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