MongoDB Atomic Operations - MongoDB

What are atomics operations in MongoDB?

MongoDB will not support multi-document atomic transactions, but it provides atomic operations on a single document. Therefore if a document has hundred fields the update statement either updates all the fields or none. Thus maintains atomicity at the document-level.

Model Data for Atomic Operations

Recommended approach for maintaining the atomicity will be to keep all the related information, which frequently gets updated together in a single document using embedded documents. This will ensure that all the updates for a single document are atomic.

Consider below products document

In this document, information of the customer is embedded who buys the product in the product_bought_by field. Now, whenever a new customer buys the product, it will first check if the product is still available using product_available field. If it is available, it will reduce the value of the product_available field as well as inserts a new customer's embedded document in the product_bought_by field. findAndModify command can be used for this functionality as it will search and update the document simultaneously.

Our approach of embedded document and using findAndModify query ensures that the product purchase information is updated only if the product is available and the whole transaction in the same query is atomic.

In contrast to this, consider a scenario where the product availability is kept and the information on who has bought the product, separately. In this scenario, it will first check if the product is available using the first query and in the second query it will update the purchase information. But, there is a possibility that between the executions of these two queries, other user might have purchased the product and it is no more available. Without knowing this, second query will update the purchase information based on the result of the first query. This will make the database inconsistent as a product is sold which is not available.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

MongoDB Topics