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!
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.
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.
