0
0
MongodbHow-ToBeginner · 3 min read

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 $max outside of a $group stage, which will cause an error.
  • Not specifying the correct field path with $ prefix, leading to unexpected results.
  • Grouping by null or 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

OperatorPurposeUsage Context
$maxFinds the maximum value of a fieldInside $group stage
$minFinds the minimum value of a fieldInside $group stage
$avgCalculates average valueInside $group stage
$sumCalculates sum of valuesInside $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.