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
Selected Reading
Get the maximum element in MongoDB collection?
To get the maximum element from a MongoDB collection, use the sort method with descending order combined with limit(1) to retrieve only the document with the highest value.
Syntax
db.collection.find().sort({"fieldName": -1}).limit(1);
Sample Data
db.demo669.insertMany([
{"Marks": 76},
{"Marks": 55},
{"Marks": 89},
{"Marks": 88},
{"Marks": 79}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ea3133c04263e90dac943d9"),
ObjectId("5ea3133f04263e90dac943da"),
ObjectId("5ea3134204263e90dac943db"),
ObjectId("5ea3134504263e90dac943dc"),
ObjectId("5ea3134e04263e90dac943dd")
]
}
Display All Documents
db.demo669.find();
{ "_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 }
Get Maximum Element
db.demo669.find().sort({"Marks": -1}).limit(1);
{ "_id": ObjectId("5ea3134204263e90dac943db"), "Marks": 89 }
How It Works
-
sort({"Marks": -1})arranges documents in descending order by the Marks field -
limit(1)returns only the first document from the sorted result - The combination gives you the document with the maximum value
Conclusion
Use sort({"field": -1}).limit(1) to efficiently retrieve the document with the maximum value in any field. This approach works for both numeric and string fields in MongoDB collections.
Advertisements
