$min
The `$min` operator is used to retrieve the minimum value for a specified field within aggregation stages like `$group`, `$bucket`, `$bucketAuto`, or `$setWindowFields`. It's particularly useful in summarizing data or finding the smallest value in a dataset. When used as a field update operator, it updates a field only if the new value is less than the current value.
Syntax
$min: <expression>
Parameters
expression
objectrequiredSpecifies the field or computed value to determine the minimum value.
Examples
Sample Data
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"name": "Lakeshore Retail | DJ Equipment Stop",
"sales": {
"salesByCategory": [
{ "categoryName": "DJ Headphones", "totalSales": 35921 }
],
"fullSales": 3700
}
}
Using $min in $group
Calculate the minimum sales value for each category.
This query groups documents by sales category and calculates the minimum sales within each category.
Query:
db.stores.aggregate([
{ $unwind: "$sales.salesByCategory" },
{
$group: {
_id: "$sales.salesByCategory.categoryName",
minSales: {
$min: "$sales.salesByCategory.totalSales"
}
}
}
])
Output:
[
{ "_id": "Christmas Trees", "minSales": 391 },
{ "_id": "Nuts", "minSales": 257 },
{ "_id": "Camping Tables", "minSales": 171 },
{ "_id": "Music Theory Books", "minSales": 323 },
{ "_id": "Fortified Wine", "minSales": 521 }
]
Using $min in $bucket
Create buckets based on sales values and calculate the minimum sales value for each bucket.
This query creates sales buckets and finds the minimum value in each bucket.
Query:
db.stores.aggregate([
{
$bucket: {
groupBy: "$sales.totalSales",
boundaries: [0, 1000, 5000, 10000],
default: "Other",
output: {
minSales: { $min: "$sales.totalSales" }
}
}
}
])
Output:
[
{ "_id": 1000, "minSales": 1000 },
{ "_id": "Other", "minSales": null },
{ "_id": 0, "minSales": 108 },
{ "_id": 5000, "minSales": 5001 }
]