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
Get maximum and minimum value in MongoDB?
To get the maximum and minimum values from a collection in MongoDB, use the $max and $min aggregation operators within a $group stage. This approach efficiently processes all documents to find the extreme values in a specified field.
Syntax
db.collection.aggregate([
{
$group: {
_id: null,
MaximumValue: { $max: "$fieldName" },
MinimumValue: { $min: "$fieldName" }
}
}
]);
Sample Data
db.maxAndMinDemo.insertMany([
{ "Value": 98 },
{ "Value": 97 },
{ "Value": 69 },
{ "Value": 96 },
{ "Value": 99 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd698a357806ebf1256f129"),
ObjectId("5cd698af57806ebf1256f12a"),
ObjectId("5cd698b357806ebf1256f12b"),
ObjectId("5cd698b657806ebf1256f12c"),
ObjectId("5cd698b957806ebf1256f12d")
]
}
Display all documents in the collection ?
db.maxAndMinDemo.find().pretty();
{ "_id": ObjectId("5cd698a357806ebf1256f129"), "Value": 98 }
{ "_id": ObjectId("5cd698af57806ebf1256f12a"), "Value": 97 }
{ "_id": ObjectId("5cd698b357806ebf1256f12b"), "Value": 69 }
{ "_id": ObjectId("5cd698b657806ebf1256f12c"), "Value": 96 }
{ "_id": ObjectId("5cd698b957806ebf1256f12d"), "Value": 99 }
Example
Find the maximum and minimum values in the "Value" field ?
db.maxAndMinDemo.aggregate([
{
$group: {
_id: null,
MaximumValue: { $max: "$Value" },
MinimumValue: { $min: "$Value" }
}
}
]);
{ "_id": null, "MaximumValue": 99, "MinimumValue": 69 }
Key Points
- Set
_id: nullto group all documents together for collection−wide calculations. -
$maxand$minoperators work with numeric, date, and string values. - Use
$fieldNamesyntax to reference the field containing values to compare.
Conclusion
The aggregation framework with $max and $min operators provides an efficient way to find extreme values in MongoDB collections. Group all documents with _id: null to calculate collection−wide maximum and minimum values.
Advertisements
