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
Get the maximum mark records from a collection with documents in MongoDB
To get the maximum mark records from a collection in MongoDB, use the $sort and $limit aggregation operators to sort documents by marks in descending order and retrieve only the top records.
Syntax
db.collection.aggregate([
{ $sort: { marks: -1 } },
{ $limit: numberOfRecords }
]);
Sample Data
Let us create a collection with student documents containing marks −
db.students.insertMany([
{ "StudentName": "Chris", "marks": 85 },
{ "StudentName": "Bob", "marks": 92 },
{ "StudentName": "David", "marks": 78 },
{ "StudentName": "Mike", "marks": 95 },
{ "StudentName": "Alice", "marks": 88 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("..."),
ObjectId("..."),
ObjectId("..."),
ObjectId("..."),
ObjectId("...")
]
}
Display all documents from the collection −
db.students.find();
{ "_id": ObjectId("..."), "StudentName": "Chris", "marks": 85 }
{ "_id": ObjectId("..."), "StudentName": "Bob", "marks": 92 }
{ "_id": ObjectId("..."), "StudentName": "David", "marks": 78 }
{ "_id": ObjectId("..."), "StudentName": "Mike", "marks": 95 }
{ "_id": ObjectId("..."), "StudentName": "Alice", "marks": 88 }
Example: Get Top 3 Maximum Mark Records
Following is the query to get the maximum mark records from the collection −
db.students.aggregate([
{ $sort: { marks: -1 } },
{ $limit: 3 }
]);
{ "_id": ObjectId("..."), "StudentName": "Mike", "marks": 95 }
{ "_id": ObjectId("..."), "StudentName": "Bob", "marks": 92 }
{ "_id": ObjectId("..."), "StudentName": "Alice", "marks": 88 }
How It Works
-
$sort: { marks: -1 }− Sorts documents in descending order by marks field -
$limit: 3− Restricts the output to only the first 3 documents after sorting - The combination returns the top 3 students with highest marks
Conclusion
Use $sort with -1 for descending order followed by $limit in an aggregation pipeline to efficiently retrieve the maximum mark records from a MongoDB collection.
Advertisements
