MongoDB Aggregation $limit

MongoDB Aggregation $limit 🚦

In MongoDB, the $limit stage is used in an Aggregation Pipeline to restrict the number of documents passed to the next stage or returned as output.

What does $limit do?

  • Returns only the first N documents

  • Improves performance by reducing data early

  • Similar to LIMIT in 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()

$limitlimit()
Aggregation stageCursor method
Used in pipelineUsed with find()
Works with $groupCannot group

Example:



Best Practices ⚠️

  • Use $limit after $sort

  • Use $limit early for performance (when possible)

  • Combine with $skip for pagination


Common Mistakes ❌

  • Using $limit before $sort

  • Passing 0 or negative numbers

  • Expecting sorted results without $sort


Quick Recap 🧠


 

You may also like...