What are Atomic Operations in MongoDB?

In MongoDB, a write operation on a single document is atomic. For fields that must be updated together, embedding the field within the same document ensures that the field can be updated automatically. For example, consider a situation where you need to maintain information on books including the number of copies available for checkout as well as the current checkout information. The available copies and the checkout information should be in sync. As such, embedding the available field and the checkout field within the same document ensures that you can update the two fields automatically.


title:”MongoDB:The Definitive Guide”,

author:[“Kristina Chodorow”,”Mike Dirolf”],

published_date: ISODATE(“2010-09-24”),





checkout:[{by: “joe”, date: ISODATE(“2012-10-15”0}]

Then to update with new checkout information, you can use the db.collection.updateOne() method to automatically update both the available field and checkout field.


{ _id:123456789, available: {$gt: 0}},


$inc: { available : -1},

$push : { checkout : { by : “abc”, date: new Date()}}



The operation returns a document that contains information on the status of the operation.

{“acknowledged” : true, “matchedCount” : 1, “modifiedCount” : 1}

The matchedCount field shows that 1 document matched the update condition, and matchedCount shows that the operation updated 1 document. If no documents matched the update condition, the matchedCount and modifiedCount would be 0 and would indicate that you could not check out the book