What is Atomic Operations in MongoDB

If You are interested to learn about the analyzing Queries


Even if a write action updates many embedded documents inside of a single document in MongoDB, the operation is still considered atomic on the level of the single document.

The suggested method for maintaining atomicity would be to use embedded documents to retain all the related information that is regularly modified together in a single document. By doing this, it would be ensured that any update to a single document is atomic.

Assume we have created a collection with name productDetails and inserted a documents in it as shown below −

{ "ok" : 1 }
> db.productDetails.insert(
		"product_name": "Samsung S3",
		"category": "mobiles",
		"product_total": 5,
		"product_available": 3,
		"product_bought_by": [
				"customer": "john",
				"date": "7-Jan-2014"
				"customer": "mark",
				"date": "8-Jan-2014"
WriteResult({ "nInserted" : 1 })

The product bought by field in this document contains information on the customer who purchased the item. The product available field will now be used to determine whether the product is still available before a new consumer purchases it. If possible, we will lower the value of the product available column and add the embedded document from the new client to the product bought by field. For this functionality, we’ll use the findAndModify command because it searches and modifies the content simultaneously.


Our strategy of combining a findAndModify query and an embedded document ensures that the product purchase information is changed only when the product is actually available. Additionally, since this transaction is a single query, it is atomic in its whole.

Consider the alternative, in which we might have kept the details of who purchased the thing and the product’s availability separate. In this instance, we will use the first query to see if the product is accessible.

The purchase information will then be updated in the second query. However, it’s possible that some other user may have bought the item between the execution of these two searches, making it no longer available. Without being aware of this, our second query will use the answer to our first query to update the purchase information. The database will become inconsistent as a result since we sold a product that was out of stock.

Modelling Data in MongoDB for Atomicity


A write operation on a single document in MongoDB is atomic. Fields that must be modified simultaneously can be updated atomically if they are embedded within the same page.

Consider a scenario where you need to keep track of book information, such as how many copies are available for checkout and the details of the current checkout.

All relevant data must be kept in a single document that is regularly updated in order to guarantee atomicity in MongoDB. Embedded documents can be used to generate a single document of this type, as demonstrated below. All updates to a single document are guaranteed to be atomic by embedded documents. 

The following is an illustration of an item purchase document:

Initially, use the command: to create a database with the name “atomic mongo.”

employ atomic mongo

Next, use the command: to construct a collection underneath it.


Now use the following command to add the data to the collection:

db.atomic.save ({ 
...    "_id":101, 
...    "item_name": "Realme GT Neo2", 
...    "category": "handset", 
...    "warranty_period": 2, 
...    "city": "Jaipur", 
...    "country": "India", 
...    "item_total": 10, 
...    "item_available": 5, 
...    "item_bought_by": [ 
...       { 
...          "customer": "Mohit", 
...          "date": "20-Nov-2021" 
...       }, 
...       { 
...          "customer": "Akash", 
...          "date": "19-Nov-2021" 
...       }, 
...       { 
...          "customer": "Ankit", 
...          "date": "18-Nov-2021" 
...       }, 
...       { 
...          "customer": "Ishan", 
...          "date": "17-Nov-2021" 
...       } 
...    ] 
... }); 
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 101 }) 

Some Commonly Used Commands in MongoDB atomic operations:

  • $Bit
  • $Rename
  • $Pop
  • $Pull
  • $Push
  • $Inc
  • $Unset
  • $Set

Commands in MongoDB atomic operations

Now, let’s see the details of these commands in MongoDB atomic operations.

i. $Set

It is used to specify a key and update the key.

{ $set : { field : value } }

ii. $Unset

Remove a key.

{ $unset : { field : 1} }

iii. $Inc

Numeric value of the document keys to increase or decrease operations.

{ $inc : { field : value } }

iv. $Push

It is used to add values to fields.

{ $push : { field : value } }

v. $Pull

To delete a field from an array.

{ $pull : { field : _value } }

vi. $Pop

Deletes first or last element.

{ $pop : { field : 1 } }

vii. $Rename

Modify the field.

{ $rename : { old_field_name : new_field_name } }

viii. $Bit

Bit operations, integer type.

{$bit : { field : {and : 5}}}

So, this was all about objectId and atomic operations in MongoDB. Hope, you liked our explanation.

Performing atomic updates

There are two types of atomic updates we can use: 

  1. updateOne(): With this method we can update and modify only a single document in a collection. 
  2. updateMany(): With this method we can update and modify multiple documents in a collection. 


A write operation on a single document in MongoDB is atomic. When fields must be updated at the same time, embedding them within the same document ensures that the fields can be updated atomically.  


Let’s update the above example we have taken earlier: 

        "_id" : "101", 
        "item_name" : "Realme GT Neo2", 
        "category" : "handset", 
        "warranty_period" : 2, 
        "city" : "Jaipur", 
        "country" : "India", 
        "item_total" : 10, 
        "item_available" : 5, 
        "item_bought_by" : [ 
                        "customer" : "Mohit", 
                        "date" : "20-Nov-2021" 
                        "customer" : "Akash", 
                        "date" : "19-Nov-2021" 
                        "customer" : "Ankit", 
                        "date" : "18-Nov-2021" 
                        "customer" : "Ishan", 
                        "date" : "17-Nov-2021" 
                        "customer" : "Madan", 
                        "date" : "18-Nov-2021" 

Write the following code to implement the updateOne() method in the above example: 

db.atomic.updateOne({_id : 101}, {$push: {item_bought_by:{ $each: [{"customer" : "Vikas", "date" : "17-Nov-2021"},{"customer" : “Bhavesh”, "date" : "16-Nov-2021"}]} }})


The above code will return: 

Perform MongoDB Atomic Operations

You can check the updated documents with the pretty and find method: 

Perform MongoDB Atomic Operations


With the help of updateMany(), we can update more than two documents in the database collection. When a single write operation (e.g. db.collection.updateMany()) modifies multiple documents, the modification of each document is atomic, but the operation as a whole is not atomic. 


     upsert: <boolean>, 
     writeConcern: <document>, 
     collation: <document>, 
     arrayFilters: [ <filterdocument1>, ... ], 
     hint:  <document|string>        // Available starting in MongoDB 4.2.1 


First, create another document in the collection “atomic” with the same fields we used earlier. 

Follow the below code to create new document: 

db.atomic.save ({ 
...    "_id":102, 
...    "item_name": "CrossBeats Ace", 
...    "category": "Smart Watch", 
...    "warranty_period": 2, 
...    "city": "Jaipur", 
...    "country": "India", 
...    "item_total": 10, 
...    "item_available": 10, 
...    "item_bought_by": [ 
...    ] 
... }); 
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 101 }) 

Write the following code to implement the updateMany() method: 

db.atomic.updateMany({city : "Jaipur"}, {$inc: { item_available: -2}, $push: {item_bought_by:{ $each: [{"customer" : "Aachal","date": "17-Nov-2021"},{"customer" : "Khushi","date":"16-Nov-2021"}]} }}); 


The above code will return: 

{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 } 

Use the find and pretty method to check the documents available now in the collection.  

Perform MongoDB Atomic Operations
Perform MongoDB Atomic Operations

In the above example, we have used the data of customers who have purchased both handset and Smart Watch and updated them into the documents of _id: 101 & _id: 102 with the help of updateMany() method. 

As you can see, updateMany() method has updated both the documents in the database. 

Using atomic operations in real world scenarios

We discussed the implementation of atomic operations in MongoDB. MongoDB does not handle transactions involving multiple documents. However, as this article’s example of an item purchase shows, we may still accomplish atomicity in MongoDB by using a single document.

Although it is not possible to work with jobs involving many documents, employing atomic actions in MongoDB is straightforward. As a result, MongoDB will allow atomic operations in a range of circumstances starting with version 4.0.

There are numerous real-world problems where we can use an atomic operation, such as in a purchase record. It will prevent mutual exclusions, thereby preventing data corruption in a variety of ways. 

Examine the source codes in the article carefully and follow them as you see fit. After a few practice rounds, you will be able to apply the atomic operation in real-world problems as needed. 


Hence, we have studied about atomic operations and objectid in MongoDB. Along with ObjectId constructor and static methods. In addition, we studied the model of MongoDB Atomic Operations with commands.

What is Atomic Operations in MongoDB
Show Buttons
Hide Buttons