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 query on top N rows in MongoDB?
To query the top N rows in MongoDB, use the aggregation framework with $sort and $limit operators. This approach allows you to sort documents by any field and retrieve only the specified number of top results.
Syntax
db.collection.aggregate([
{ $sort: { fieldName: 1 } }, // 1 for ascending, -1 for descending
{ $limit: N } // N = number of documents to return
]);
Sample Data
db.topNRowsDemo.insertMany([
{ "StudentName": "Larry", "Score": 78 },
{ "StudentName": "Chris", "Score": 45 },
{ "StudentName": "Mike", "Score": 65 },
{ "StudentName": "Adam", "Score": 55 },
{ "StudentName": "John", "Score": 86 }
]);
Method 1: Top N by Score (Descending)
Get the top 3 students with highest scores ?
db.topNRowsDemo.aggregate([
{ $sort: { Score: -1 } },
{ $limit: 3 }
]);
{ "_id": ObjectId("..."), "StudentName": "John", "Score": 86 }
{ "_id": ObjectId("..."), "StudentName": "Larry", "Score": 78 }
{ "_id": ObjectId("..."), "StudentName": "Mike", "Score": 65 }
Method 2: Top N with Filtering
Get top 3 students alphabetically who scored above 60 ?
db.topNRowsDemo.aggregate([
{ $match: { Score: { $gt: 60 } } },
{ $sort: { StudentName: 1 } },
{ $limit: 3 }
]);
{ "_id": ObjectId("..."), "StudentName": "John", "Score": 86 }
{ "_id": ObjectId("..."), "StudentName": "Larry", "Score": 78 }
{ "_id": ObjectId("..."), "StudentName": "Mike", "Score": 65 }
Key Points
-
$sortmust come before$limitto get accurate top N results - Use
-1for descending order (highest first) and1for ascending - Combine with
$matchto filter before sorting and limiting
Conclusion
Use MongoDB's aggregation pipeline with $sort and $limit to efficiently query top N rows. Always sort before limiting to ensure you get the correct top results based on your criteria.
Advertisements
