Web Programming TutorialsLearn How to Use Atomic Operations in MongoDB

Learn How to Use Atomic Operations in MongoDB

Atomic Operations

In this article, we are going to discuss about creating atomic operations in MongoDB. An atomic operation in a database is an undividable and complex series of database operations such that either all operation will occur, or nothing will occur. The term atomicity is used to guarantee that there will be no partial database update i.e. either the entire lot of updates will happen or nothing will happen at all and the partial changes (if any) will be rolled back. The partial update will cause more damages than rejecting the whole series outright. Therefore, operatic operations are very important in every databases including MongoDB.

Database atomicity can be further explained with the help of the ACID transaction properties. ACID acronym stands for Atomicity, Consistency, Isolation, and Durability.

• Atomicity in simple words can be explained as each transaction should be “either all or nothing”.
• The consistency property will guarantee that any transaction happened on a database will always bring the database from one to another valid state.
• The isolation property will guarantee the sequential execution of the concurrent transactions i.e., one after the other.
• The durability property will guarantee that once a transaction is committed then it will always remain permanent irrespective of database crashes, power loss, or errors.

MongoDB atomic operations
The following are the important points to remember for MongoDB atomic operations.

• There is no support for multi-document atomic transactions in MongoDB.
• MongoDB provides atomic operations only on single documents. E.g., if a document has fifty fields then the update statement will either update all the fifty fields or nothing.
• Atomicity is only maintained at the document-level.

Model Data for Atomic Operations in MongoDB
As discussed before, we can maintain atomicity in MongoDB only through keeping all the related information together in a single document which we update repeatedly. Such a single document can be created with the help of embedded documents as shown below. Embedded documents will make sure that all the updates made on a single document are atomic. The following is an example of item purchase document.

Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\Users\Aparajita>cd C:\Program Files\MongoDB\Server\3.2\bin

C:\Program Files\MongoDB\Server\3.2\bin>mongo.exe
MongoDB shell version: 3.2.10
connecting to: test
> use AtomicMongoDB
switched to db AtomicMongoDB
> db.AtominMongoDB.save ({
...    "_id":101,
...    "item_name": "Apple iPhone 7",
...    "category": "handset",
...    "warranty_period": 5,
...    "city": "Toronto",
...    "country": "Canada",
...    "item_total": 10,
...    "item_available": 6,
...    "item_bought_by": [
...       {
...          "customer": "Mohit",
...          "date": "6-May-2017"
...       },
...       {
...          "customer": "Aparajita",
...          "date": "5-May-2017"
...       },
...       {
...          "customer": "Anita",
...          "date": "4-May-2017"
...       },
...       {
...          "customer": "Abhishek",
...          "date": "3-May-2017"
...       }
...    ]
... });
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 101 }) 
> db.AtominMongoDB.find().pretty();
{
        "_id" : 101,
        "item_name" : "Apple iPhone 7",
        "category" : "handset",
        "warranty_period" : 5,
        "city" : "Toronto",
        "country" : "Canada",
        "item_total" : 10,
        "item_available" : 6,
        "item_bought_by" : [
                {
                        "customer" : "Mohit",
                        "date" : "6-May-2017"
                },
                {
                        "customer" : "Aparajita",
                        "date" : "5-May-2017"
                },
                {
                        "customer" : "Anita",
                        "date" : "4-May-2017"
                },
                {
                        "customer" : "Abhishek",
                        "date" : "3-May-2017"
                }
        ]
}
>

The above document is an embedded document where we have embedded the customer information according to item purchased in the item_bought_by field. This single document will help to check whether the item is available in stock or not when a customer places a new order through item_available field. If an item is available then we will subtract the item_available field by 1 and insert a new customer name and date of purchase details in the item_bought_by field of the document. In the following example, we are going to use findAndModify command for this functionality. This command helps to search and update the document simultaneously.

> db.AtominMongoDB.findAndModify({
...    query:{_id:101,item_available:{$gt:0}},
...    update:{
...       $inc:{item_available:-1},
...       $push:{item_bought_by:{customer:"CP Jain",date:"6-May-2017"}}
...    }
... });
{
        "_id" : 101,
        "item_name" : "Apple iPhone 7",
        "category" : "handset",
        "warranty_period" : 5,
        "city" : "Toronto",
        "country" : "Canada",
        "item_total" : 10,
        "item_available" : 6,
        "item_bought_by" : [
                {
                        "customer" : "Mohit",
                        "date" : "6-May-2017"
                },
                {
                        "customer" : "Aparajita",
                        "date" : "5-May-2017"
                },
                {
                        "customer" : "Anita",
                        "date" : "4-May-2017"
                },
                {
                        "customer" : "Abhishek",
                        "date" : "3-May-2017"
                }
        ]
}
> db.AtominMongoDB.find().pretty();
{
        "_id" : 101,
        "item_name" : "Apple iPhone 7",
        "category" : "handset",
        "warranty_period" : 5,
        "city" : "Toronto",
        "country" : "Canada",
        "item_total" : 10,
        "item_available" : 5,
        "item_bought_by" : [
                {
                        "customer" : "Mohit",
                        "date" : "6-May-2017"
                },
                {
                        "customer" : "Aparajita",
                        "date" : "5-May-2017"
                },
                {
                        "customer" : "Anita",
                        "date" : "4-May-2017"
                },
                {
                        "customer" : "Abhishek",
                        "date" : "3-May-2017"
                },
                {
                        "customer" : "CP Jain",
                        "date" : "6-May-2017"
                }
        ]
}
>

Explanation of above DB script
• Here, we first searched item with the ID as 101.
• When such item is found, we are incrementing the item_available field by -1 and updating the item_bought_by field by adding the customer name and the date of purchase of item.
• Next, we print the overall purchase detail by using find and pretty method. Here, we can observe that the item_available field has reduced from 6 to 5 and new customer details have been added in the item_bought_by field.

Conclusion
In this chapter, we discussed about creating atomic operations in MongoDB. The MongoDB does not support multi-document atomic transactions. However, we can still create atomicity in MongoDB through a single document, which we showed in this article through an item purchase article.

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -