0
0
MongodbHow-ToBeginner · 3 min read

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 _id expression.
  • _id: The grouping key; use null to 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 $min outside of a $group stage, 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

OperatorDescriptionUsage Context
$minReturns the minimum value of a field or expressionInside $group stage
$groupGroups documents for aggregationAggregation pipeline stage
_idSpecifies grouping key; use null for all documentsInside $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.