WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

MongoDB - Atomic Operations


MongoDB does not support multi-document atomic transactions.

it does provide atomic operations on a single document.

Model Data for Atomic Operations

The recommended approach to maintain atomicity would be to keep all the related information, which is frequently updated together in a single document using embedded documents. Consider the following products document
{
    "_id":1,
    "product_name": "Google Pixel 3 Just Black 128",
    "category": "mobiles",
    "product_total": 5,
    "product_available": 3,
    "product_bought_by": [
        {
            "customer": "David",
            "date": "4-Oct-2018"
        },
        {
            "customer": "Anderson",
            "date": "5-Oct-2018"
        }
    ]
}
Here customer who buys the product in the product_bought_by field.whenever a new customer buys the product, we will first check if the product is still available using product_available field. But We can use findAndModify command for this functionality because it searches and updates the document in the same go.
>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"}} 
   }    
})
findAndModify query makes sure that the product purchase information is updated only if it the product is available.



Welookups is optimized for learning.Copy right 2018 kumar aditya singh .
All Right Reserved and you agree to have read and accepted our term and condition.
All Rights Reserved.