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
How to find minimum value in MongoDB?
To find the minimum value in MongoDB, you can use sort() along with limit(1). This sorts documents in ascending order and returns only the first document containing the minimum value.
Syntax
db.yourCollectionName.find().sort({yourFieldName: 1}).limit(1);
Create Sample Data
Let us create a collection with student marks to demonstrate finding the minimum value ?
db.findMinValueDemo.insertMany([
{"StudentMarks": 78},
{"StudentMarks": 69},
{"StudentMarks": 79},
{"StudentMarks": 59},
{"StudentMarks": 91}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c8f80ea2f684a30fbdfd59f"),
ObjectId("5c8f80f02f684a30fbdfd5a0"),
ObjectId("5c8f80f32f684a30fbdfd5a1"),
ObjectId("5c8f80f82f684a30fbdfd5a2"),
ObjectId("5c8f80fb2f684a30fbdfd5a3")
]
}
Display all documents from the collection ?
db.findMinValueDemo.find().pretty();
{ "_id": ObjectId("5c8f80ea2f684a30fbdfd59f"), "StudentMarks": 78 }
{ "_id": ObjectId("5c8f80f02f684a30fbdfd5a0"), "StudentMarks": 69 }
{ "_id": ObjectId("5c8f80f32f684a30fbdfd5a1"), "StudentMarks": 79 }
{ "_id": ObjectId("5c8f80f82f684a30fbdfd5a2"), "StudentMarks": 59 }
{ "_id": ObjectId("5c8f80fb2f684a30fbdfd5a3"), "StudentMarks": 91 }
Example: Find Minimum Value
Here is the query to find the minimum StudentMarks value ?
db.findMinValueDemo.find().sort({StudentMarks: 1}).limit(1);
{ "_id": ObjectId("5c8f80f82f684a30fbdfd5a2"), "StudentMarks": 59 }
How It Works
-
sort({StudentMarks: 1})− Sorts documents in ascending order by StudentMarks field -
limit(1)− Returns only the first document from the sorted result - The combination gives you the document with the minimum value
Conclusion
Use sort({field: 1}).limit(1) to find the minimum value in MongoDB. This approach sorts documents in ascending order and returns the first document containing the smallest value for the specified field.
Advertisements
