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

In MongoDB, arithmetic operators enable you to perform mathematical operations on values within database documents. Mastery of these operators is crucial for effective data manipulation. There are two arithmetic operators: $inc (increment) and $mul (multiply).

  • $inc: Adjusts a field's value by adding a specified amount. This operator can be used for both addition and subtraction.
  • $mul: Multiplies a field's value by a specified factor. This operator can be used for both multiplication and division.

These operators are particularly useful for scenarios such as adjusting stock quantities or recalculating values based on changing conditions.

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 field for "X-Men" by 1 using the operator.

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