- Reference >
- Operators >
- Aggregation Pipeline Operators >
- Group Accumulator Operators >
- $min (aggregation)
$min (aggregation)¶
- $min¶
Returns the lowest value that results from applying an expression to each document in a group of documents that share the same group by key.
$min is an accumulator operator available only in the $group stage.
$min has the following syntax:
{ $min: <expression> }
For more information on expressions, see Expressions.
Behavior¶
在 2.4 版更改.
If some, but not all, documents for the $min operation have either a null value for the field or are missing the field, the $min operator only considers the non-null and the non-missing values for the field.
If all documents for the $min operation have null value for the field or are missing the field, the $min operator returns null for the minimum value.
Before 2.4, if any of the documents for the $min operation were missing the field, the $min operator would not return any value. If any of the documents for the $min had the value null, the $min operator would return a null.
Example¶
Consider a sales collection with the following documents:
{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:00:00Z") }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-02-03T09:00:00Z") }
{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-03T09:05:00Z") }
{ "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-02-15T08:00:00Z") }
{ "_id" : 5, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-02-15T09:05:00Z") }
Grouping the documents by the item field, the following operation uses the $min accumulator to compute the minimum amount and minimum quantity for each grouping.
db.sales.aggregate(
[
{
$group:
{
_id: "$item",
minQuantity: { $min: "$quantity" }
}
}
]
)
The operation returns the following results:
{ "_id" : "xyz", "minQuantity" : 5 }
{ "_id" : "jkl", "minQuantity" : 1 }
{ "_id" : "abc", "minQuantity" : 2 }