For enquiries call:

Phone

+1-469-442-0620

April flash sale-mobile

HomeBlogWeb DevelopmentHow To Perform MongoDB Atomic Operations

How To Perform MongoDB Atomic Operations

Published
05th Sep, 2023
Views
view count loader
Read it in
9 Mins
In this article
    How To Perform MongoDB Atomic Operations

    Explore how to create atomic operations in MongoDB. In a database, an atomic operation is an undivided and complex series of database operations in which either all or none of the operations occur. The term atomicity refers to the guarantee that no partial database updates will occur, i.e., either the entire set of updates will occur, or nothing will occur, and any partial changes (if any) will be rolled back.  

    What is Atomicity?

    In database terminology, atomic operations are a series of chained and sophisticated database operations. In this series, either all or none of the series' aspects will be altered. There is no such thing as a partial database change in atomic operations. 

    The partial update will cause more harm than outright rejecting the entire series. As a result, operational operations are critical in all databases, including MongoDB. 

    There is only room for complete database updates and changes in atomic operations. If any partial updates are made, the entire database will be rolled back. 

    In cases where a partial update would cause more harm than rolling back, we use atomic operations. In the real world, we may need to maintain our database in this manner in some cases. We will go over it in greater detail in the latter part of this article. 

    We can clearly explain atomic operations in MongoDB by using the acronym ACID, which stands for Atomicity, Consistency, Isolation, and Durability. 

    • Here is a simple rule ofatomicityfor every single operation, “either all or none.” 
    • Theconsistencyproperty will play a crucial role in atomicity. It will ensure that each transaction will ultimately lead to a valid state of some kind. 
    • Theisolationproperty of the database will play a part in guaranteeing the systematic process of the concurrent transaction, which means one by one. 
    • Finally, thedurabilityproperty will come into play. This property ensures the permanency of the database after each database transaction regardless of errors, crashes, and power loss. 

    Modelling Data in MongoDB for Atomicity

    As previously discussed, the only way to maintain atomicity in MongoDB is to keep all related information in a single document that is updated on a regular basis. A single document of this type can be created using embedded documents, as shown below. Embedded documents ensure that all updates to a single document are atomic.  

    An example of an item purchase document is shown below: 

    First, create a database with name "atomic_mongo" using the command: 

    use atomic_mongo 

    Now, create a collection under it with the command: 

    db.createCollection(“atomic”) 

    Now, add the data in the collection using following command: 

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

    Now, you can write the following query to print the document of the database: 

    > db.atomic.find().pretty(); 

    Output:

    Perform MongoDB Atomic Operations

    The document above is an embedded document in which we have embedded customer information based on the item purchased in the item bought by field. This single document will assist in determining whether an item is in stock or not when a customer places a new order using the item available field. If an item is available, we will deduct one from the item available field and add a new customer name and date of purchase details of item_bought_by field of the document. 

    Now, for this functionality we will use the findAndModify command. This command allows you to search and update the document at the same time: 

    > db.atomic.findAndModify({ 
    ... ...    query:{_id:101,item_available:{$gt:0}}, 
    ... ...    update:{ 
    ... ...       $inc:{item_available:-1}, 
    ... ...       $push:{item_bought_by:{customer:"Madan",date:"18-Nov-2021"}} 
    ... ...    } 
    ... ... }); 
    { 
            "_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" 
                    } 
            ] 
    } 

    To check the modified document in the database, use the following query: 

    > db.atomic.find().pretty(); 

    Perform MongoDB Atomic Operations

    In this case, we first searched for an item with the ID 101; when such an item is found, we increment the item available field by -1 and update the item bought by field by adding the customer's name and the date of purchase. 

    Then, using the find and pretty method, we print the overall purchase detail. The item available field has been reduced from 5to 4and new customer details have been added to the item bought by field. 

    Our approach of embedding the document and utilising the findAndModify query ensures that the product purchase information is only updated if the product is available. And because the entire transaction is contained within the same query, it is atomic. 

    Consider the alternative scenario in which we kept the product availability and the information on who purchased the product separate. In this case, we'll use the first query to see if the product is available. The purchase information will then be updated in the second query. However, it is possible that in the time between these two queries, another user purchased the product, and it is no longer available. Without realising it, our second query will update the purchase information based on the results of the first query. This will cause inconsistency in the database because we sold a product that is no longer available. 

    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. 

    updateOne()

    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.  

    Example:

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

    Output: 

    The above code will return: 

    Perform MongoDB Atomic Operations

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

    db.atomic.find().pretty() 

    Perform MongoDB Atomic Operations

    updateMany()

    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. 

    Syntax: 

     db.collection.updateMany( 
       <filter>,
       <update>, 
       { 
         upsert: <boolean>, 
         writeConcern: <document>, 
         collation: <document>, 
         arrayFilters: [ <filterdocument1>, ... ], 
         hint:  <document|string>        // Available starting in MongoDB 4.2.1 
       } 
    ) 
    

    Example:

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

    Output: 

    The above code will return: 

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

    Perform MongoDB Atomic Operations

    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. 

    Unlock your coding potential with our programming course certificate. Gain the skills and knowledge to excel in the tech industry. Enroll now!

    Using atomic operations in real world scenarios

    We talked about how to implement atomic operations in MongoDB. Multi-document atomic transactions are not supported by MongoDB. However, we can still achieve atomicity in MongoDB by using a single document, as demonstrated in this article with an item purchase example. 

    Although working with multi-document tasks is not possible, using atomic operations in MongoDB is simple. As a result, beginning with version 4.0, MongoDB will support atomic operations in a variety of scenarios. 

    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. 

    Profile

    Abhresh Sugandhi

    Author

    Abhresh is specialized as a corporate trainer, He has a decade of experience in technical training blended with virtual webinars and instructor-led session created courses, tutorials, and articles for organizations. He is also the founder of Nikasio.com, which offers multiple services in technical training, project consulting, content development, etc.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon