

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 }
- Related Questions & Answers
- Get the maximum mark records from a collection with documents in MongoDB
- Get the maximum mark records from a collection with documents in MongoDB query
- What is the MongoDB Capped Collection maximum allowable size?
- Get names of all keys in the MongoDB collection?
- Get the top most document from a MongoDB collection
- Get the size of a collection in MongoDB using conditions?
- Get all fields names in a MongoDB collection?
- Get execution stats in MongoDB for a collection
- Removing an array element from a MongoDB collection
- Retrieve only the queried element in an object array in MongoDB collection?
- Get the count of the number of documents in a MongoDB Collection?
- Get maximum and minimum value in MongoDB?
- How to get array from a MongoDB collection?
- How to get unique values from MongoDB collection?
- MongoDB query to pull array element from a collection?
Advertisements