How to Use $max in Aggregation in MongoDB: Syntax and Examples
In MongoDB aggregation, use the
$max operator to find the highest value of a specified field within grouped documents. It is typically used inside the $group stage to return the maximum value for each group or across the entire collection.Syntax
The $max operator is used inside the $group stage of an aggregation pipeline. It takes a field expression and returns the maximum value found in that group.
_id: Defines the group key.maxValue: The field name to store the maximum value.$max: The operator to find the maximum value of the specified field.
json
{
$group: {
_id: "<grouping_field>",
maxValue: { $max: "$<field_to_compare>" }
}
}Example
This example groups documents by the category field and finds the maximum price in each category.
mongodb
db.products.aggregate([
{
$group: {
_id: "$category",
maxPrice: { $max: "$price" }
}
}
])Output
[
{ "_id": "electronics", "maxPrice": 1200 },
{ "_id": "books", "maxPrice": 45 },
{ "_id": "clothing", "maxPrice": 150 }
]
Common Pitfalls
Common mistakes when using $max include:
- Using
$maxoutside of a$groupstage, which will cause an error. - Not specifying the correct field path with
$prefix, leading to unexpected results. - Grouping by
nullor an incorrect field, which aggregates all documents into one group unintentionally.
mongodb
/* Wrong usage: $max outside $group */ db.products.aggregate([ { $max: "$price" } ]) /* Correct usage: $max inside $group */ db.products.aggregate([ { $group: { _id: null, maxPrice: { $max: "$price" } } } ])
Quick Reference
| Operator | Purpose | Usage Context |
|---|---|---|
| $max | Finds the maximum value of a field | Inside $group stage |
| $min | Finds the minimum value of a field | Inside $group stage |
| $avg | Calculates average value | Inside $group stage |
| $sum | Calculates sum of values | Inside $group stage |
Key Takeaways
Use $max inside the $group stage to find the highest value in grouped documents.
Always prefix the field name with $ when using $max to specify the field path.
Grouping by the correct field is essential to get meaningful maximum values.
Using $max outside $group will cause errors in the aggregation pipeline.