How to Use $min in Aggregation in MongoDB: Syntax and Examples
In MongoDB aggregation, use the
$min operator to find the smallest value of a specified field across documents or within grouped data. It is typically used inside the $group stage to return the minimum value for a field. For example, { $group: { _id: null, minValue: { $min: "$fieldName" } } } finds the minimum value of fieldName.Syntax
The $min operator is used inside the $group stage of an aggregation pipeline to calculate the minimum value of a specified field or expression.
$group: Groups input documents by the specified_idexpression._id: The grouping key; usenullto group all documents together.$min: Takes a field path or expression and returns the smallest value in the group.
json
{
$group: {
_id: <grouping_key>,
minValue: { $min: "$fieldName" }
}
}Example
This example finds the minimum score from a collection of student documents using aggregation.
mongodb
db.students.aggregate([
{
$group: {
_id: null,
minScore: { $min: "$score" }
}
}
])Output
[ { "_id" : null, "minScore" : 56 } ]
Common Pitfalls
Common mistakes when using $min include:
- Using
$minoutside of a$groupstage, which will cause an error. - Not specifying the field path as a string with
$prefix (e.g.,"$score"), leading to unexpected results. - Grouping by a field unintentionally, which changes the aggregation output.
mongodb
/* Wrong: $min used outside $group */ db.students.aggregate([ { $min: "$score" } ]) /* Right: $min inside $group */ db.students.aggregate([ { $group: { _id: null, minScore: { $min: "$score" } } } ])
Quick Reference
| Operator | Description | Usage Context |
|---|---|---|
| $min | Returns the minimum value of a field or expression | Inside $group stage |
| $group | Groups documents for aggregation | Aggregation pipeline stage |
| _id | Specifies grouping key; use null for all documents | Inside $group stage |
Key Takeaways
Use $min inside the $group stage to find the smallest value in grouped documents.
Always prefix the field name with $ inside $min, like "$fieldName".
Set _id to null in $group to aggregate over all documents without grouping.
Do not use $min outside of aggregation stages like $group.
Check your grouping key to avoid unexpected grouping results.