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).
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 stock_quantity
field for "X-Men" by 1 using the $inc
operator.
Here's how we do it:
JavaScript1use comic_book_store_db 2 3db.comic_books.updateOne( 4 { title: "X-Men" }, 5 { $inc: { stock_quantity: -1 } } 6);
The updateOne()
method targets the document where title
is "X-Men". The $inc
operator is used to decrement the stock_quantity
by 1.
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:
JavaScript1use comic_book_store_db 2 3db.comic_books.updateOne( 4 { title: "Daredevil" }, 5 { $mul: { stock_quantity: 5 } } 6);
The updateOne()
method targets the document where title
is "Daredevil". The $mul
operator multiplies the stock_quantity
by 5.
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!