Perform min/max with MongoDB aggregation

To find minimum and maximum values in MongoDB, use the $min and $max operators within the aggregation pipeline's $group stage. These operators analyze numeric fields across documents and return the smallest and largest values respectively.

Syntax

db.collection.aggregate([
    {
        $group: {
            _id: null,
            maxValue: { $max: "$fieldName" },
            minValue: { $min: "$fieldName" }
        }
    }
]);

Sample Data

Let's create a collection with student marks ?

db.demo251.insertMany([
    { "Marks": 78 },
    { "Marks": 87 },
    { "Marks": 56 },
    { "Marks": 76 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e46c0001627c0c63e7dba74"),
        ObjectId("5e46c0031627c0c63e7dba75"),
        ObjectId("5e46c0061627c0c63e7dba76"),
        ObjectId("5e46c00c1627c0c63e7dba77")
    ]
}

Display all documents to verify the data ?

db.demo251.find();
{ "_id": ObjectId("5e46c0001627c0c63e7dba74"), "Marks": 78 }
{ "_id": ObjectId("5e46c0031627c0c63e7dba75"), "Marks": 87 }
{ "_id": ObjectId("5e46c0061627c0c63e7dba76"), "Marks": 56 }
{ "_id": ObjectId("5e46c00c1627c0c63e7dba77"), "Marks": 76 }

Example: Find Min/Max Marks

Use the aggregation pipeline to find the highest and lowest marks ?

db.demo251.aggregate([
    {
        $group: {
            _id: null,
            MaxMarks: { $max: "$Marks" },
            MinMarks: { $min: "$Marks" }
        }
    }
]);
{ "_id": null, "MaxMarks": 87, "MinMarks": 56 }

Key Points

  • $max returns the highest value from the specified field across all grouped documents
  • $min returns the lowest value from the specified field across all grouped documents
  • Setting _id: null groups all documents together for overall min/max calculation
  • Both operators work with numeric, date, and string values

Conclusion

The $min and $max operators in MongoDB's aggregation pipeline efficiently calculate minimum and maximum values across document collections. Use them within $group stages to analyze numeric data and find extreme values.

Updated on: 2026-03-15T02:03:57+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements