How to perform Atomic Operations on MongoDB?

How to perform Atomic Operations on MongoDB?

Originally published at&nbsp;<a href="" target="_blank"></a>

The NoSQL database system has been able to gain momentum in the past few years due to its flexibility and other benefits. Mongo is the leader when it comes to NoSQL. There are plenty of amazing features of MongoDB, and one of them are atomic operations. In the upcoming sections of this article, we will go deep into atomic operations, its use, and how you can apply it to your projects.

Before moving forward to checking out how we can apply atomic operations in MongoDB, we will be looking at some of the critical points that you need to keep in your mind in regards to MongoDB:

  • MongoDB does not support atomicity for multi-document transactions. However, version 4.0 onwards will support multi-document transactions in several cases.
  • It is only possible to use the atomicity feature of MongoDB in a single document (not in case of version 4.0). Suppose, there is a document that consists of 35 fields. In that document, there will either be updates in all 35 fields or none.
  • The atomicity feature is only limited to the document level.

If you want to jump into the NoSQL database, you should consider MongoDB certification. It will give you a strong foundation and skills to use MongoDB to solve real-world problems. There is a considerable job demand for MongoDB professionals.

  1. Introduction to Atomic Operations

The atomic operations in database terminology is a chained and sophisticated database operations series. In this series, either all aspects of the series will be affected, or nothing will be altered. In atomic operations, there is no such thing as a partial database change.

In atomic operations, there is only a room for complete database updates and changes. In case of any partial updates, the whole database will roll back.

We use atomic operations in a case where the partial update will create more harm in comparison to rolling back. There are some instances in the real world where we need to maintain our database in this manner. In the latter part of this article, we will discuss more in depth about it.

We can explain atomic operations in MongoDB clearly with the use of ACID, a.k.a. Atomicity, Consistency, Isolation, and Durability.

  • Here is a simple rule of atomicity for every single operation, “either all or none.”
  • The consistency property will play a crucial role in atomicity. It will ensure that each transaction will ultimately lead to a valid state of some kind.
  • The isolation property of the database will play a part in guaranteeing the systematic process of the concurrent transaction, which means one by one.
  • Finally, the durability property will come into play. This property ensures the permanency of the database after each database transaction regardless of errors, crashes, and power loss.
2.Modeling e-Commerce Products in MongoDB

We should maintain atomicity in MongoDB by compiling all the related information in a single document, which will update consistently. We can create such type of consistency via embedded documents. The embedded is for ensuring that every single update that takes place in the document is atomic.

Here is how the document looks like for representing item purchase information.

2.1 Creating a new product

Let’s say we have an e-Commerce app and we want to model a product on MongoDB with atomic operations. We can do something like this:

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

// create an iPhone product with embedded buyers{
  "_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

In the above document, we have created a model, embedded document. We have produced a report from the purchase in the item_bought_by field. This single document will manage everything about the purchase and the stock. In this document, it will see whether the item that the customer orders are in the stock or not. The customer’s order processes through the item_available field.

2.2 Decreasing count on a purchase

In the case of availability, we will subtract the itemavailable field by 1. After we complete that part, we will record the information of the customer, and, i.e., name and the purchase date, in the itembought_by field. We will again look at another document where we will be using the findAndmodify statement to fulfill this purpose. By using findAndmodify statement, the document will perform search and update activity simultaneously in the report.

buying a product
  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
// {
//   "_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"
//     }
//   ]
// }

In the above document, we searched for the item, setting the ID as 1111. If the system finds such a thing, we activate the subtraction function and deduct 1 in the item_available field. We will also update the field item_bought_by in which we insert the name of the customer along with the purchase date.

Finally, we print the full information with the function, find and pretty method. We can see that the item_available field will come down from 6 to 5 while adding the customer name and the purchase date in the item_bought_by field.

One more example to make you more precise about the use of atomic operations in MongoDB

2.3 Modeling books on MongoDB and performing atomic operations

In the above case, we dealt mainly with the product order and the record keeping of customers. In this example, we will be using the function of the simple book store and make it work out in MongoDB via atomic operations.

Let’s suppose in that book store, and we need to maintain the record of books along with the number of copies available for checkout, including crucial details about checkout.

We should sync the number of copies available, and checkout information must for the program to work. We will be embedding the checkout and the available field for ensuring that the two areas will be updated atomically.

create a book on mongo
// create a new book{
  _id: 222222,
  title: "Data Structures & Algorithms in JavaScript",
  author: [ "Adrian Mejia" ],
  published_date: ISODate("2019-02-15"),
  pages: 216,
  language: "English",
  publisher_id: "Independent",
  available: 156,
  checkout: [ { by: "Ivan", date: ISODate("2019-04-14") } ]

Updating the checkout field with new information is essential. We will be using db.collection.updateOne() method for atomically updating available and checkout field.

Purchasing a book
  _id: 222222,
  available: { $gt: 0 }
}, {
  $inc: { available: -1 },
  $push: {
    checkout: {
      by: "Abby",
      date: new Date()

The above command will return the following:

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

The matchedCount field is responsible for comparing the condition for updates. We can see that 1 document fulfilled the requirements due to which the operation updated 1 document (modifiedCount).

There could also be the case where no documents are matched, according to the update condition. In that situation, both the matchedCount and modifiedCount field would be 0. What this means is that you will not be able to purchase the book and continue with a checkout process.

3. Final Say

Finally, we have finished the topic of how you can use atomic operations via MongoDB. It was not that difficult, was it? Although it is not possible to work out with multi-document tasks, but using atomic operations in MongoDB is simple. With that said, MongoDB starting from version 4.0 will be supporting atomic operations in numerous scenarios.

There are plenty of real-world issues where we can use an atomic operation like in purchase record. It will prevent mutual exclusions; hence, it will stop the corruption of data in many ways.

Take a close look at the source codes in the article and follow it as you see fit. After practicing for a few times, you can naturally apply the atomic operation in the real-world problems where needed.

Do you have any confusions? If yes, feel free to leave a comment below. We will reply to your comment for clearing out your difficulties. In case you want to add more insights, you can put forward your opinion in the comment below.

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

Web Development Services

Web Development Services

As one of the best Web Application Development Company, it provides a fine quality mobile app development service at an affordable price. Especially, it encourage start-ups that have unique ideas, by offering a more competitive price

HireFullStackDeveloperIndia is rated as one of the top Web Application Development Company in India by various industry magazines and review sites. They have a right blend of award-winning designers, expert programmers and Google certified digital marketers which make them a unique one-stop solution for hundreds of our clients, spread across all countries.

A Good website reflects not only your business but also it is one of the main factors why a potential customer would convert into Client. A good website design helps increase traffic driving leads to grow business. The best web design company create a custom design for each corporate website so as to help them meet their business goals.

Get Quote:

Hire Web Development Company in Chicago, USA

Hire Web Development Company in Chicago, USA

When you plan to develop a website, then you look forward to getting a complete solution, and hiring a Web Development Company in Chicago is the best result for this need.

Do you wonder what a full-stack developer is?

Let’s understand it further with this post…

A full stack developer is the one who apprehends the complete web development process and can fit with his expertise on any level of the development process.

However, finding a highly qualified full-stack developer is a tad tricky part of the business, as you need to understand and adopt the right technical expertise to initiate your web project.

If you are worried of picking the wrong resource, which could only hamper your business revenue goal through the website development then you need to consider the right approach suggested in this post, which can further help you hire full stack developer for your specific business needs.

What Does All Full Stack Developer do?

When it comes to web application development, then there is a different set of development, like for frontend and backend. They can be bifurcated into two basic divisions; one who builds the interfaces and rest who builds software engines behind it.

A full stack web developer can perform all these aspects, ranging from databases, front-end (client side) to server-side scripts. These developers have the capability of coding and even designing to a certain extent, also they can manage the complete project.

Full Stack Developers Are Responsible For:

  • Code programs and applications
  • Coordinate other developers and team members
  • Troubleshoot issues
  • Outline testing techniques for web apps
  • Manage web development

Technical expertise of a full-stack developer involves:

  • JavaScript
  • HTML
  • PHP
  • CSS
  • Angular
  • MySQL
  • Ruby
  • MongoDB
  • Node
  • Apache, etc.

Hiring a Full Stack programmer from HireFullStackDeveloperIndia is a lucrative deal, as we have a strong brood of highly experienced developers, who understand every bit of technology and the new market trends, and accordingly, update their knowledge bank.

Our development procedure involves a flexible assignation of different expertise of technologies and has catered our development services to many renowned brands globally.

Our team of full-stack developers is well-equipped with the complete knowledge of front-end and back-end technologies, which together offer a great solution. Our team holds the expertise to handle and manage the entire development and implementation process, whether it is for a website, web app or mobile app.

We are the master of many different technologies and have comprehensive knowledge about pertinent technologies consisting of MEAN stack, front end, back end, UI, server infrastructure, etc.

This is the sole reason, we are picked by a maximum number of businesses across the globe, needless to say, and we are competent enough to accomplish the entire development process based on the requirements of the esteemed clientele.

So without any further delay, simply get in touch with us, and help your business to scale higher…

You can hire the extremely talented and experienced team of full stack developer to form us at the most reasonable cost of $12-$18 hr and mark a change in your business with an effective web solution.