Atomic Operation in MongoDB

MongoDB does not support Atomic Transaction over multiple Documents. However, it provides Atomic Operations on a single Document. Therefore, if a Document has hundreds of fields, the update command will either update all those fields or not update any fields, thus maintaining Atomicity at the Document level.

MongoDB does not support Atomic Transaction over multiple Documents. However, it provides Atomic Operations on a single Document. Therefore, if a Document has hundreds of fields, the update command will either update all those fields or not update any fields, thus maintaining Atomicity at the Document level.

Data modeling for Atomic Transaction

The recommended method to maintain Atomicity will be to keep all relevant information, which is updated regularly in a single Document, using Embedded Documents . This ensures that all updates to a single Document are Atomic.

You follow the following products document :

 { "_id" : 1 , "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" } ] } 

In this Document, we have embedded the information of the customer who purchased the product, into the product_bought_by field. Now, whenever a new customer purchases the product, we first check if the product is available using the product_available field. If available, we will reduce the value of the product_available field as well as insert the new client's Embedded Document into the product_bought_by field. We will use the findAndModify command for this feature because it searches and updates the Document at the same time.

 > db . products . findAndModify ({ query :{ _id : 2 , product_available :{ $gt : 0 }}, update :{ $inc :{ product_available :- 1 }, $push :{ product_bought_by :{ customer : "rob" , date : "9-Jan-2014" }} } }) 

The Embedded Document method and the query usage findAndModify ensures that product purchase information is only updated if the product is available. And all this transaction is Atomic.

Conversely, assuming a situation, we may have kept information about the availability of the product and information about who bought the product separately. In this situation, we first check the availability of the product by using the first query. Then, in the second query, we will update the purchase information. However, what may happen between the execution of the above two queries is that some users have purchased the product and it is no longer available. Without looking at this, our second query will update the purchase information based on the results of the first query. This creates conflicts in the database because we have sold a product that is not available.

According to Tutorialspoint

Previous article: Query analysis in MongoDB

Next lesson: Advanced indexing activity in MongoDB

4 ★ | 1 Vote