Hello again! Now that we've grasped the fundamentals of MongoDB update operations and arithmetic updates, it's time to delve deeper into some specific operators — $min
and $max
. Let's dive in!
The $max
and $min
operators allow us to update fields within our documents by storing either the maximum or minimum value between their current value and a new value provided. These operators are especially useful when you need to keep track of the highest or lowest record of something.
For instance, imagine you need to monitor the highest and lowest customer ratings for each comic book in a collection. Whenever a new rating is submitted, you can use $max
and $min
to potentially update the stored ratings.
Here's how they function:
$max
: Updates a specified field to a new value only if the new value is greater than the current value.$min
: Updates a specified field to a new value only if the new value is less than the current value.
Let's implement the scenario mentioned above, where we keep track of the highest and lowest ratings left by readers. Every time a reader leaves a review with a rating, we need to check if these values require an update. If the new rating is greater than the current maximum rating, we update the maximum rating. Similarly, if the new rating is less than the current minimum rating, we update the minimum rating. Here is how the update query will look if a user leaves a rating of 8:
JavaScript1use comic_book_store_db 2 3db.comic_books.updateOne( 4 { title: "Doctor Strange" }, 5 { $max: { highest_customer_rating: 8 } } 6) 7 8db.comic_books.updateOne( 9 { title: "Doctor Strange" }, 10 { $min: { lowest_customer_rating: 8 } } 11)
In the code snippet, we first select the "Doctor Strange" document with { title: "Doctor Strange" }
. Then, we apply the $max
operator to highest_customer_rating
, comparing the existing value with 8
. Similarly, we use the $min
operator to potentially update lowest_customer_rating
.
Congratulations! You've now added powerful tools to your MongoDB skill set. By mastering the use of $min
and $max
operators, you are becoming more proficient with MongoDB update operations. In the upcoming practice session, you'll get the chance to apply $min
and $max
operations to different fields in our comic book dataset. Keep practicing and exploring, and as always, happy coding!