Home >>MongoDB Tutorial >MongoDB Atomic Operations

MongoDB Atomic Operations

Model Data for Atomic Operations

The recommended atomicity preservation approach would be to store all relevant information that is regularly modified in a single document using embedded documents. This will make sure all of the updates are atomic for a single document.

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

>db.createCollection("products")
{ "ok" : 1 }
> db.productDetails.insert(
	{
		"_id":1,
		"product_name": "Samsung S3",
		"category": "mobiles",
		"product_total": 5,
		"product_available": 3,
		"product_bought_by": [
			{
				"customer": "john",
				"date": "5-Aug-2020"
			},
			{
				"customer": "mark",
				"date": "5-Aug-2020"
			}
		]
	}
)
WriteResult({ "nInserted" : 1 })
>

In this document, we have included in the product-bought-by field the details of the customer who buys the product. Now we can first check whether the item is still available using the product-available field when a new customer buys the product. If available, we will decrease the value of the product-available field and insert the embedded document of the potential employee into the product-bought-by field. For this feature, we will use the findAndModify command because the document is searched and modified the same way.

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

Our embedded document approach and the use of the findAndModify query means that the product purchase information is only modified if the product is available. And this whole transaction, which is in the same query, is atomic.

In comparison to this, consider the case in which we would have retained the availability of the product and the details separately about who bought the product. In this case, using the first query, we will first check whether the product is available. Then we will correct the purchase data in the second query. However, it is possible that the product has been purchased by some other user between the execution of these two queries and is no longer usable. Without understanding this the purchase information will be updated by our second query based on the result of our first query. This would make the database inconsistent since a product which is not available has been sold by us.


No Sidebar ads