MongoDB Aggregation $limit
MongoDB Aggregation $limit 🚦
What does $limit do?
Returns only the first N documents
Improves performance by reducing data early
Similar to
LIMITin SQL
Basic Syntax
📌 <number> must be a positive integer
1️⃣ Simple $limit Example
Get only 5 students
2️⃣ $limit with $sort (Most Common Use)
Top 3 oldest students
📌 $sort must come before $limit
3️⃣ $limit with $match
First 5 BA students
4️⃣ Pagination using $skip + $limit
Page 2 (5 records per page)
5️⃣ $limit after $group
Top 3 courses by student count
SQL vs MongoDB $limit
SQL
MongoDB
$limit vs limit()
$limit | limit() |
|---|---|
| Aggregation stage | Cursor method |
| Used in pipeline | Used with find() |
Works with $group | Cannot group |
Example:
Best Practices ⚠️
Use
$limitafter$sortUse
$limitearly for performance (when possible)Combine with
$skipfor pagination
Common Mistakes ❌
Using
$limitbefore$sortPassing 0 or negative numbers
Expecting sorted results without
$sort
