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