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

  • $sort must come before $limit to get accurate top N results
  • Use -1 for descending order (highest first) and 1 for ascending
  • Combine with $match to 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.

Updated on: 2026-03-15T00:43:33+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements