Tutorial on updating records in MongoDB

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In our last tutorial, we added an new record.  Let’s update that record with a replacement where we replace the entire document.  Instead of high temperature of 100 Celsisus, our replacement will have the value of 105 instead.

Replacement Update

First we have to find the record that we want to update using the “query” object and findOne() method.  This record has “state” = “New State” …

updating mongodb

updating mongodb

Once we got the record in question, the record data will be in “doc”.  We construct a second “query2” which contains the _id of the record found.  This is the record being replaced.  It will be replaced by our “doc” except with doc[‘high’][‘celsius’] value replaced by the new value of 105.

We call the update() method which returns a callback containing the number of records updated.  In this case, it should be one.

In-Place Update

But perhaps a more efficient way to update this case is to do an in-place update rather than updating the entire document.  This is how…

using mongodb set operator

using mongodb set operator

Like before, we query for the record “state” = “New State”.  But this time we use the operator object with ‘$set’ in the update() method.  Again, the output should be one document updated.


What if you want to update multiple documents all at once. In this next example, we will wipe out the high.celsius property from all our document in one operation…

multi-update on mongodo

multi-update on mongodo

The query empty object means to query all documents.   Note that we have an option object passed into our update method.  The option has multi as true.

Find and Modify

The problem with replacement update is that the initial query and the update are atomic.  The in-place update is better, but if after the update you retrieve the document, there is still a time lag.

The findAndModify() method is atomic as is demonstrated here where we change “New State” into “New State2” …



The sort object is sometimes needed in case there are more than one document that meets the criteria of the query.  findAndModify() will update the first document that it finds.

The operator sets the new value.

The option ‘new’ of true tells it to returned the newly modified doc as opposed to the original unchanged doc.