How to Use $min and $max in MongoDB: Syntax and Examples
In MongoDB,
$min and $max are used in update operations to conditionally set a field to a lower or higher value, respectively. They can also be used in aggregation pipelines to find minimum or maximum values across documents.Syntax
The $min and $max operators are primarily used in update commands to update a field only if the new value is less than ($min) or greater than ($max) the current field value.
Basic syntax in an update operation:
{
$min: { : }
} {
$max: { : }
} Where:
- <field> is the document field to update.
- <value> is the value to compare and possibly set.
In aggregation, $min and $max are used as accumulator operators to find minimum or maximum values across documents.
mongodb
db.collection.updateOne(
{ _id: 1 },
{ $min: { score: 50 } }
)
db.collection.updateOne(
{ _id: 1 },
{ $max: { score: 90 } }
)Example
This example shows how to use $min and $max in update operations to conditionally update a user's score.
mongodb
use testdb; // Insert a sample document db.users.insertOne({ _id: 1, name: "Alice", score: 75 }); // Try to update score to 50 using $min (will update because 50 < 75) db.users.updateOne( { _id: 1 }, { $min: { score: 50 } } ); // Check updated document printjson(db.users.findOne({ _id: 1 })); // Try to update score to 90 using $max (will update because 90 > 50) db.users.updateOne( { _id: 1 }, { $max: { score: 90 } } ); // Check updated document printjson(db.users.findOne({ _id: 1 }));
Output
{ "_id" : 1, "name" : "Alice", "score" : 50 }
{ "_id" : 1, "name" : "Alice", "score" : 90 }
Common Pitfalls
Common mistakes when using $min and $max include:
- Using them outside update operations where they are not supported.
- Expecting them to work like simple assignment operators; they only update if the condition is met.
- Not considering the field type; comparisons depend on the BSON type ordering.
Example of a wrong usage and the correct way:
mongodb
// Wrong: Using $min in a find query (invalid) db.collection.find({ $min: { score: 50 } }); // Right: Use $min in update operation db.collection.updateOne( { _id: 1 }, { $min: { score: 50 } } );
Quick Reference
| Operator | Usage | Effect |
|---|---|---|
| $min | Update operator | Sets field to value if value is less than current field value |
| $max | Update operator | Sets field to value if value is greater than current field value |
| $min | Aggregation accumulator | Returns minimum value from group of documents |
| $max | Aggregation accumulator | Returns maximum value from group of documents |
Key Takeaways
Use $min and $max in update operations to conditionally update fields based on comparison.
$min updates the field only if the new value is less than the current value.
$max updates the field only if the new value is greater than the current value.
In aggregation, $min and $max find minimum or maximum values across documents.
Avoid using $min and $max outside their supported contexts like update or aggregation.