mongodb atomic operations
  • How to Execute MongoDB Atomic Operations to Maintain Data Integrity

Featured Image Caption: MongoDB Atomic Operations

The NoSQL data set framework has had the option to acquire momentum in the past couple of years because of its adaptability and different advantages. Mongo is the pioneer with regard to NoSQL. There are a lot of astounding features of MongoDB, and the most complex of them are atomic operations. So, do you want to execute data integrity with MongoDB atomic operations? You have landed at the right place. This guide will assist you more in this respect, so just scroll down and get cutting-edge knowledge about this database of NoSQL.

Get the brief info about Atomic Operations.

The atomic operations in terms of the database is a chained and sophisticated database operations series. In this series, either all parts of the series will be afflicted, or nothing will be modified.

Generally, there is no such thing as a partial database change in atomic operations. However, there is just a space for complete database updates and changes. In case of any partial or incomplete updates, the entire database will be rolled back. There are a few cases in the real world where you need to maintain your database in this manner.

The partial or unfulfilled update will cause more harm than outright rejection during the whole series. Resultantly, operational operations are assumed as more critical in all databases, including MongoDB.

Here you will get a clear explanation of atomic operations in MongoDB by using the specific acronym – ACID, which is the abbreviation of Atomicity, Consistency, Isolation, and Durability.

Atomicity:

Here is a simple and straightforward rule of atomicity for each and every operation, “either all or none.”

Consistency:

The consistency property will assume a critical part in atomicity. It will grant assurance that each transaction will, after all, lead to a valid state of some kind.

Isolation:

The isolation property of the data set will have an impact in ensuring the systematic process of the coincident transaction, and that implies individually.

Durability:

At last, the durability property will become an integral factor. This property guarantees the permanency of the database after every database transaction aside from errors, crashes, and power loss.

How to execute MongoDB Atomic Operations

First of all, here are some key points that you have to keep in mind while performing MongoDB atomic operations. Such as.

  • In MongoDB, there is no support in multi-document atomic transactions.
  • MongoDB grants atomic operations just on a single document. For instance, if a document has sixty fields, then the update statement will either update all the sixty fields or nothing.
  • Atomicity is only maintained or executed at the document level.

Modeling data in MongoDB for Atomic Operations

As discussed earlier, you can maintain atomicity in MongoDB only if you keep all the corresponding information piled up in a single document which you update time and again. Such a single document can be constructed with the assistance of embedded documents. The reason is that embedded documents will give assurance that all the updates made on a single document are atomic.

To clear this whole scenario, let’s see a specific example of an item purchase document, which is going to discuss below.

In the first place, we own an e-Commerce app and model the products on MongoDB along with atomic operations.

At the moment, add the data in the collection using the following command.

creating a product on MongoDB
use AtomicMongoDB;
// => switched to db AtomicMongoDB

// create an iPhone product with embedded buyers
db.AtominMongoDB.save({
“_id”: 1111,
“item_name”: “Apple iPhone Xs Max 512GB”,
“price”: 1450,
“category”: “handset”,
“warranty_period”: 5,
“city”: “Toronto”,
“country”: “Canada”,
“item_total”: 10,
“item_available”: 6,
“item_bought_by”: [{
“customer”: “Bob”,
“date”: “6-Feb-2019”
},
{
“customer”: “Alice”,
“date”: “5-Jan-2019”
},
{
“customer”: “Anita”,
“date”: “4-Dec-2018”
},
{
“customer”: “Abhishek”,
“date”: “10-Dec-2018”
}
]
});
// => WriteResult({ “nMatched” : 0, “nUpserted” : 1, “nModified” : 0, “_id” : 1111 })

// Verify the document was saved
db.AtominMongoDB.find().pretty();

The document above is an embedded document in which you have embedded customer information based upon the item purchased in the item bought by field.

This single document will help you in figuring out whether an item is in stock or not when a customer places a new order using the item available field. If an item is available, you will deduct one from the item available field and add a new customer name and date of purchase details of the item_bought_by field of the document.

Now, for this functionality, you will use the FindAndModify command. This command permits you to search and update the document at the same time:

buying a product
db.AtominMongoDB.findAndModify({
query: {
_id: 1111,
item_available: {
$gt: 0
}
},
update: {
$inc: {
item_available: -1
},
$push: {
item_bought_by: {
customer: “Adrian”,
date: “14-Mar-2019”
}
}
}
});

// => returns found document

// Verify new customer was added and stock number decreased
db.AtominMongoDB.find().pretty();
// {
// “_id”: 1111,
// “item_name”: “Apple iPhone Xs Max 512GB”,
// “price”: 1450,
// “category”: “handset”,
// “warranty_period”: 5,
// “city”: “Toronto”,
// “country”: “Canada”,
// “item_total”: 10,
// “item_available”: 5,
// “item_bought_by”: [{
// “customer”: “Bob”,
// “date”: “6-Feb-2019”
// },
// {
// “customer”: “Alice”,
// “date”: “5-Jan-2019”
// },
// {
// “customer”: “Anita”,
// “date”: “4-Dec-2018”
// },
// {
// “customer”: “Abhishek”,
// “date”: “10-Dec-2018”
// },
// {
// “customer”: “Adrian”,
// “date”: “14-Mar-2019”
// }
// ]
// }

For this situation, you originally looked for an item with the ID 101; when such an item is found, you increase the item accessible field by – 1 and update the item purchased by field by adding the client’s name and the date of procurement.

Then, at that point, using a fine and awesome strategy, you can print the overall purchase detail. The item available field has been reduced from 5 to 4, whereas new customer details have been added to the item bought by the field.

The approach of embedding the document and utilizing the findAndModify query make sure that if the product is available, only then product purchase information is updated. And because the whole transaction is contained within the same query, it is atomic.

Conclusion

In the whole article, the focus point remained on how to execute or perform MongoDB atomic operations in order to maintain data integrity. Multi-document atomic transactions are not upheld via MongoDB. Although, you can still accomplish atomicity in MongoDB by using a single document, as demonstrated in this article with an item purchase example.

Although it’s not possible to work with multi-document tasks, utilizing atomic operations in MongoDB is simple. Consequently, starting with version 4.0, MongoDB will support atomic operations in a variety of scenarios.

By Steve Parkar
who has extensive experience with inbound marketing for various industries like eCom, Mfg, Real-estate, Education, and advertising. Having worked with a Digital Marketing Agency, he has gained expertise in digital content creation, SME acquisition, and white hat linking.

Member since February, 2022
View all the articles of Steve Parkar.

Like it? Share it!

FacebookTwitter / XLinkedInPin ItBufferRedditEmailWhatsapp

Do You Enjoy Writing and Have Something Interesting to Share?

You are at the right place. Inspiring MeMe is the world's fastest growing platform to share articles and opinions. We are currently accepting articles, blogs, personal experiences & tips and would love to have you onboard.

Share your article today!
alert

All images and content mentioned herewith have been shared by the authors/contributors as on dated February 4, 2022. We do not hold any liability for infringement or breach of copyright of third parties across the spectrum. Pictures shared by authors/contributors are deemed to be authorized by them likewise. For any disputes, we shall not be held responsible.

Previous

Some of the Best Mixer from the Leading Brands in India

Next

What is a SIM Only Plan? The Benefits of Choosing One over a Contract

Leave a Reply

© 2015-2024 Inspiring MeMe | All rights reserved.