Introduction to MongoDB $max Operator

The $max operator is one of the aggregation pipeline operators in MongoDB that is used to compute the maximum value of a given field. The $max operator is used to find the maximum value of a given field in the aggregation pipeline, and then output it to the result set.

Syntax

The syntax for the $max operator is as follows:

{ $max: <expression> }

Here, <expression> refers to the field or expression for which the maximum value needs to be computed. The $max operator aggregates and calculates the field or expression, and outputs the result to the result set.

Use Cases

The $max operator can be used to compute the maximum value of a field in a document. For example, in a collection that stores student grade information, where each document contains the student’s name and exam score, the $max operator can be used to calculate the highest score of all students in the collection.

Examples

Here are three examples of using the $max operator.

Example 1: Finding the Highest Score

Consider a grade book collection where each document contains a student’s name and math score. We want to find the highest score of all students.

db.scores.aggregate([
  {
    $group: {
      _id: null,
      maxScore: { $max: "$mathScore" }
    }
  }
])

In this aggregation pipeline, we first group all documents into one group using $group. The $max operator finds the highest value of the mathScore field in each group, and stores it in a new field called maxScore. Since we do not need to group, _id is set to null.

Example 2: Finding the Highest Sales for Each Group

Consider a sales order collection where each document contains a product name, sales date, and sales amount. We want to find the highest sales for each product.

db.sales.aggregate([
  {
    $group: {
      _id: "$product",
      maxSales: { $max: "$amount" }
    }
  }
])

In this aggregation pipeline, we first group all documents by the product field using $group. The $max operator finds the highest value of the amount field in each group, and stores it in a new field called maxSales.

Example 3: Finding the Maximum Date in All Documents

Consider a log collection where each document contains a timestamp and some log information. We want to find the maximum timestamp in all documents.

db.logs.aggregate([
  {
    $group: {
      _id: null,
      maxDate: { $max: "$timestamp" }
    }
  }
])

In this aggregation pipeline, we first group all documents into one group using $group. The $max operator finds the highest value of the timestamp field in each group, and stores it in a new field called maxDate. Since we do not need to group, _id is set to null.

Conclusion

The $max operator is used to find the highest value of a field in the aggregation pipeline and store it in a new field. The $max operator is useful when processing documents of numeric, date, or other types.