Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get maximum and minimum value in MongoDB?
Use $max and $min operator along with aggregate framework to get the maximum and minimum value. Let us first create a collection with documents −
> db.maxAndMinDemo.insertOne({"Value":98});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd698a357806ebf1256f129")
}
> db.maxAndMinDemo.insertOne({"Value":97});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd698af57806ebf1256f12a")
}
> db.maxAndMinDemo.insertOne({"Value":69});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd698b357806ebf1256f12b")
}
> db.maxAndMinDemo.insertOne({"Value":96});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd698b657806ebf1256f12c")
}
> db.maxAndMinDemo.insertOne({"Value":99});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd698b957806ebf1256f12d")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.maxAndMinDemo.find().pretty();
This will produce the following output −
{ "_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 }
Following is the query to max and min in MongoDB −
> db.maxAndMinDemo.aggregate([
{ "$group": {
"_id": null,
"MaximumValue": { "$max": "$Value" },
"MinimumValue": { "$min": "$Value" }
}}
]);
This will produce the following output −
{ "_id" : null, "MaximumValue" : 99, "MinimumValue" : 69 }Advertisements