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
-
Economics & Finance
Selected Reading
Getting the highest value of a column in MongoDB?
To get the highest value of a column in MongoDB, use the sort() method with limit(1) to retrieve the document containing the maximum value for a specific field.
Syntax
db.collection.find().sort({"fieldName": -1}).limit(1);
The -1 parameter sorts in descending order, placing the highest value first.
Sample Data
Let's create sample documents to demonstrate finding the highest value ?
db.gettingHighestValueDemo.insertMany([
{"Value": 1029},
{"Value": 3029},
{"Value": 1092},
{"Value": 18484},
{"Value": 37474},
{"Value": 88474},
{"Value": 1938474}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c900b885705caea966c5574"),
ObjectId("5c900b8d5705caea966c5575"),
ObjectId("5c900b925705caea966c5576"),
ObjectId("5c900b955705caea966c5577"),
ObjectId("5c900b9c5705caea966c5578"),
ObjectId("5c900ba75705caea966c5579"),
ObjectId("5c900bab5705caea966c557a")
]
}
Display all documents to see our data ?
db.gettingHighestValueDemo.find().pretty();
{ "_id": ObjectId("5c900b885705caea966c5574"), "Value": 1029 }
{ "_id": ObjectId("5c900b8d5705caea966c5575"), "Value": 3029 }
{ "_id": ObjectId("5c900b925705caea966c5576"), "Value": 1092 }
{ "_id": ObjectId("5c900b955705caea966c5577"), "Value": 18484 }
{ "_id": ObjectId("5c900b9c5705caea966c5578"), "Value": 37474 }
{ "_id": ObjectId("5c900ba75705caea966c5579"), "Value": 88474 }
{ "_id": ObjectId("5c900bab5705caea966c557a"), "Value": 1938474 }
Example: Getting the Highest Value
Now find the document with the highest Value ?
db.gettingHighestValueDemo.find().sort({"Value": -1}).limit(1);
{ "_id": ObjectId("5c900bab5705caea966c557a"), "Value": 1938474 }
Key Points
-
sort({"field": -1})arranges documents in descending order by the specified field -
limit(1)returns only the first document from the sorted result - This method returns the entire document, not just the maximum value
Conclusion
Use sort() with -1 for descending order and limit(1) to efficiently retrieve the document containing the highest value in any MongoDB collection field.
Advertisements
