Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Perform min/max with MongoDB aggregation
To find minimum and maximum values in MongoDB, use the $min and $max operators within the aggregation pipeline's $group stage. These operators analyze numeric fields across documents and return the smallest and largest values respectively.
Syntax
db.collection.aggregate([
{
$group: {
_id: null,
maxValue: { $max: "$fieldName" },
minValue: { $min: "$fieldName" }
}
}
]);
Sample Data
Let's create a collection with student marks ?
db.demo251.insertMany([
{ "Marks": 78 },
{ "Marks": 87 },
{ "Marks": 56 },
{ "Marks": 76 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e46c0001627c0c63e7dba74"),
ObjectId("5e46c0031627c0c63e7dba75"),
ObjectId("5e46c0061627c0c63e7dba76"),
ObjectId("5e46c00c1627c0c63e7dba77")
]
}
Display all documents to verify the data ?
db.demo251.find();
{ "_id": ObjectId("5e46c0001627c0c63e7dba74"), "Marks": 78 }
{ "_id": ObjectId("5e46c0031627c0c63e7dba75"), "Marks": 87 }
{ "_id": ObjectId("5e46c0061627c0c63e7dba76"), "Marks": 56 }
{ "_id": ObjectId("5e46c00c1627c0c63e7dba77"), "Marks": 76 }
Example: Find Min/Max Marks
Use the aggregation pipeline to find the highest and lowest marks ?
db.demo251.aggregate([
{
$group: {
_id: null,
MaxMarks: { $max: "$Marks" },
MinMarks: { $min: "$Marks" }
}
}
]);
{ "_id": null, "MaxMarks": 87, "MinMarks": 56 }
Key Points
-
$maxreturns the highest value from the specified field across all grouped documents -
$minreturns the lowest value from the specified field across all grouped documents - Setting
_id: nullgroups all documents together for overall min/max calculation - Both operators work with numeric, date, and string values
Conclusion
The $min and $max operators in MongoDB's aggregation pipeline efficiently calculate minimum and maximum values across document collections. Use them within $group stages to analyze numeric data and find extreme values.
Advertisements
