Arithmetic Updates in MongoDB

Introduction

Welcome back! In our previous MongoDB lesson, we refreshed our knowledge of the updateOne and updateMany methods, along with the $set operator. We also briefly introduced other update operators. Today, we continue exploring update operators in MongoDB, focusing on the $inc and $mul operators, which are handy for performing simple arithmetic on numeric fields. Let's dive in!

Arithmetic Updates

Understanding $inc

Imagine a sale at our comic book store — one "X-Men" comic book has been sold. To update our inventory, we will decrease the stock_quantity field for "X-Men" by 1 using the $inc operator.

Here's how we do it:

use comic_book_store_db

db.comic_books.updateOne(
  { title: "X-Men" },
  { $inc: { stock_quantity: -1 } }
);

The updateOne() method targets the document where title is "X-Men". The $inc operator is used to decrement the stock_quantity by 1.

Understanding $mul

Now, consider receiving a new shipment that multiplies our "Daredevil" comic book inventory by five. We can update our data using the $mul operator.

Here's the example:

use comic_book_store_db

db.comic_books.updateOne(
  { title: "Daredevil" },
  { $mul: { stock_quantity: 5 } }
);

The updateOne() method targets the document where title is "Daredevil". The $mul operator multiplies the stock_quantity by 5.

Summary

In this lesson, we explored how to use the $inc and $mul operators and demonstrated their practicality through examples. These tools are invaluable for real-world data management, enabling you to perform efficient updates reflective of dynamic business scenarios. Get ready to apply these concepts in the upcoming practice exercises, where you'll continue honing your MongoDB skills!

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal