Min and max values of an array in MongoDB?

To find the minimum and maximum values from array elements in MongoDB, use the $min and $max operators within an aggregation pipeline. These operators work on array fields to extract the smallest and largest values respectively.

Syntax

db.collection.aggregate([
    {
        $project: {
            "minField": { $min: "$arrayField.property" },
            "maxField": { $max: "$arrayField.property" }
        }
    }
]);

Sample Data

db.demo286.insertOne({
    "details": [
        { "Value1": 70, "Value2": 50 },
        { "Value1": 30, "Value2": 36 }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e4ac743f49383b52759cbbc")
}

View Sample Data

db.demo286.find().pretty();
{
    "_id": ObjectId("5e4ac743f49383b52759cbbc"),
    "details": [
        {
            "Value1": 70,
            "Value2": 50
        },
        {
            "Value1": 30,
            "Value2": 36
        }
    ]
}

Example: Get Min and Max Values

Find the minimum Value1 and maximum Value2 from the details array ?

db.demo286.aggregate([
    {
        $project: {
            "name": 1,
            "MinValue1": { $min: "$details.Value1" },
            "MaxValue2": { $max: "$details.Value2" }
        }
    }
]);
{
    "_id": ObjectId("5e4ac743f49383b52759cbbc"),
    "MinValue1": 30,
    "MaxValue2": 50
}

Key Points

  • $min and $max work with array fields using dot notation ($arrayField.property).
  • Use $project stage in aggregation to reshape the output with calculated min/max values.
  • These operators compare values across all array elements for the specified field.

Conclusion

The $min and $max operators in MongoDB aggregation pipelines efficiently extract minimum and maximum values from array elements. Use dot notation to target specific properties within nested array objects.

Updated on: 2026-03-15T02:18:19+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements