Model Data for Atomic Operations
The endorsed method to keep atomicity might be to preserve all of the associated data, that is often up to date together in a single file the use of embedded documents. This would ensure that each one the updates for a unmarried report are atomic.
Assume we have created a set with name productDetails and inserted a files in it as proven beneath −
>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": "7-Jan-2014"
},
{
"customer": "mark",
"date": "8-Jan-2014"
}
]
}
)
WriteResult({ "nInserted" : 1 })
>
In this record, we've got embedded the facts of the customer who buys the product within the product_bought_by area. Now, each time a new consumer buys the product, we are able to first check if the product is still available the use of product_available area. If to be had, we will lessen the fee of product_available subject in addition to insert the new purchaser's embedded record inside the product_bought_by subject. We will use findAndModify command for this functionality as it searches and updates the record within the identical pass.
>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 approach of embedded report and the usage of findAndModify query makes certain that the product buy statistics is updated only if it the product is available. And the complete of this transaction being within the identical query, is atomic.
In comparison to this, don't forget the state of affairs wherein we may additionally have kept the product availability and the information on who has offered the product, one at a time. In this example, we are able to first take a look at if the product is available the usage of the first question. Then inside the 2d query we will update the purchase records. However, it is possible that among the executions of those two queries, a few other consumer has bought the product and it is no extra available. Without knowing this, our 2nd query will replace the acquisition records primarily based at the end result of our first question. This will make the database inconsistent because we have sold a product which is not available.