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
Perform min/max with MongoDB aggregation
For min/max in MongoDB, use $min and $max. Let us create a collection with documents −
> db.demo251.insertOne({"Marks":78});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e46c0001627c0c63e7dba74")
}
> db.demo251.insertOne({"Marks":87});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e46c0031627c0c63e7dba75")
}
> db.demo251.insertOne({"Marks":56});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e46c0061627c0c63e7dba76")
}
> db.demo251.insertOne({"Marks":76});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e46c00c1627c0c63e7dba77")
}
Display all documents from a collection with the help of find() method −
> db.demo251.find();
This will produce the following output −
{ "_id" : ObjectId("5e46c0001627c0c63e7dba74"), "Marks" : 78 }
{ "_id" : ObjectId("5e46c0031627c0c63e7dba75"), "Marks" : 87 }
{ "_id" : ObjectId("5e46c0061627c0c63e7dba76"), "Marks" : 56 }
{ "_id" : ObjectId("5e46c00c1627c0c63e7dba77"), "Marks" : 76 }
Following is the query to implement min/max aggregation in MongoDB −
> db.demo251.aggregate([
... { "$group": {
... "_id": null,
... "MaxMarks": { "$max": "$Marks" },
... "MinMarks": { "$min": "$Marks" }
... }}
...])
This will produce the following output −
{ "_id" : null, "MaxMarks" : 87, "MinMarks" : 56 }Advertisements