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 the maximum element in MongoDB collection?
To get the maximum element from the collection, sort in descending order with limit. Let us create a collection with documents −
>
> db.demo669.insertOne({"Marks":76});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea3133c04263e90dac943d9")
}
> db.demo669.insertOne({"Marks":55});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea3133f04263e90dac943da")
}
> db.demo669.insertOne({"Marks":89});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea3134204263e90dac943db")
}
> db.demo669.insertOne({"Marks":88});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea3134504263e90dac943dc")
}
> db.demo669.insertOne({"Marks":79});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea3134e04263e90dac943dd")
}
Display all documents from a collection with the help of find() method −
> db.demo669.find();
This will produce the following output −
{ "_id" : ObjectId("5ea3133c04263e90dac943d9"), "Marks" : 76 }
{ "_id" : ObjectId("5ea3133f04263e90dac943da"), "Marks" : 55 }
{ "_id" : ObjectId("5ea3134204263e90dac943db"), "Marks" : 89 }
{ "_id" : ObjectId("5ea3134504263e90dac943dc"), "Marks" : 88 }
{ "_id" : ObjectId("5ea3134e04263e90dac943dd"), "Marks" : 79 }
Following is the query to get the maximum element from the collection −
> db.demo669.find().sort({"Marks":-1}).limit(1);
This will produce the following output −
{ "_id" : ObjectId("5ea3134204263e90dac943db"), "Marks" : 89 }Advertisements