MongoDB $limit Stage

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $limit?

$limit is a MongoDB aggregation stage that keeps only the first N documents from the current pipeline and drops the rest—essential for top-10 lists, paginated APIs, and trimming results early.

Remember
$limit = "keep only the first N"

{ $limit: 5 }

does NOT sort by itself
for top-N → $sort then $limit
for pages → $sort → $skip → $limit
fewer than N docs → you get all of them
{ $limit: 0 } → empty result

find().limit(N) → similar idea outside aggregation
UsePrefer
Top-N after ranking$sort + $limit
Offset pagination$skip + $limit
Random N documents$sample (not $limit)

How to Use $limit in MongoDB

Filter, order if needed, then cap with a positive integer.

  1. Optionally filter with $match.
  2. For ranked results, $sort immediately before $limit.
  3. Add { $limit: N } (positive integer).
  4. For pages, insert $skip between sort and limit.
PieceRequired?Role
N (integer)YesMax documents to keep
Prior $sortNo*Defines which “first N” means
Prior $skipNoOffset for page 2, 3, …

*Required in practice for top-N and stable pagination.

Pseudocode

Pseudocode
count = 0
for each document from prior stage:
  if count >= N:
    stop
  emit document
  count += 1

// If prior stage ends early, emit fewer than N

Cheat Sheet

Keep these facts handy while building lists and pages.

TopicDetail
TypeAggregation stage
Syntax{ $limit: N }
Top-N pattern$sort then $limit
Page pattern$sort → $skip → $limit
Page 2, size 20$skip: 20, $limit: 20
Fewer than NReturns all remaining docs
OptimizationAdjacent $sort + $limit may use top-k

Live Preview

Cap the top published articles by views (teaching model of $sort + $limit).

Published articles only, sorted by views descending.

Result
1. Node.js + MongoDB     15200
2. Intro to MongoDB      12400
3. REST API Design       11300

Worked Walkthrough — Top 3 by Views

Seven published articles. Goal: highest views first, keep three.

Calculation
$match published: true
  → 7 articles (draft dropped)

$sort views: -1
  → 15200, 12400, 11300, 8900, 7800, 6700, 5400

$limit: 3
  → keep first three only:
     Node.js + MongoDB (15200)
     Intro to MongoDB  (12400)
     REST API Design    (11300)

MongoDB Examples

We use a small articles collection. First build a top-N list, then paginate with $skip. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Eight articles with views and a published flag—enough for top-N and page demos.

mongosh
db.articles.drop()
db.articles.insertMany([
  { title: "Intro to MongoDB",    category: "Database", views: 12400, published: true },
  { title: "Aggregation Basics",  category: "Database", views: 8900,  published: true },
  { title: "Node.js + MongoDB",   category: "Backend",  views: 15200, published: true },
  { title: "Indexing Strategies", category: "Database", views: 6700,  published: true },
  { title: "Draft: Sharding",     category: "Database", views: 0,     published: false },
  { title: "REST API Design",     category: "Backend",  views: 11300, published: true },
  { title: "Schema Validation",   category: "Database", views: 5400,  published: true },
  { title: "Express Middleware",  category: "Backend",  views: 7800,  published: true }
])

db.articles.createIndex({ views: -1 })

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps eight documents in articles. Run find() to see them:

mongosh
db.articles.find({}, { title: 1, views: 1, published: 1, _id: 0 })

Read the important fields like this:

FieldExamplePlain English
views15200Sort key for top-N
publishedtrueFilter before limiting
title"REST API Design"What we show in results

How It Works

  1. Reset once. drop() keeps demos repeatable.
  2. Mixed publish state. One draft is excluded by later $match.
  3. Index on views. Helps $sort + $limit for top-N.

Example 2 — Top N

Goal: published articles only, highest views first, keep three. This is the classic leaderboard pattern.

mongosh
db.articles.aggregate([
  { $match: { published: true } },
  { $sort: { views: -1 } },
  { $limit: 3 },
  { $project: { title: 1, views: 1, _id: 0 } }
])

How It Works

  1. Filter. $match drops the unpublished draft.
  2. Rank. $sort puts highest views first.
  3. Cap. $limit: 3 keeps only the head of that list.
  4. Without sort? You would get three arbitrary published rows.

Example 3 — Pagination

Goal: page 2 with 3 articles per page, still sorted by views.

mongosh
const page = 2
const pageSize = 3
const skip = (page - 1) * pageSize   // 3

db.articles.aggregate([
  { $match: { published: true } },
  { $sort: { views: -1 } },
  { $skip: skip },
  { $limit: pageSize },
  { $project: { title: 1, views: 1, _id: 0 } }
])

// Page 1 would be skip: 0, limit: 3
// → Node.js, Intro, REST API
// Page 2 → Aggregation Basics, Express, Indexing

How It Works

  1. Same order every page. $sort first so pages do not reshuffle.
  2. Skip the previous page. Page 2 skips the first 3 rows.
  3. Limit the page size. Keep the next 3 only.
  4. Large skips. Very high offsets get expensive—use cursors for deep pages.

Edge Cases & Pitfalls

Check these before shipping list and page APIs with $limit.

order

$limit does not sort

Without $sort, “first N” is pipeline order—not highest, newest, or best.

zero

$limit: 0 returns nothing

A limit of zero is valid and yields an empty cursor. Guard bad page sizes in your app.

skip

Large $skip is costly

Skipping thousands of rows still reads them. Prefer range/cursor pagination for deep pages.

ties

Add a tie-breaker for stable pages

Equal views can shuffle between pages. Sort by views then _id (or createdAt) for consistency.

Performance Notes

ApproachCostBest for
$sort + $limit (indexed)Top-k friendlyLeaderboards / top-N
$match then limitFewer docs earlyFiltered lists
Huge $skipReads skipped rowsAvoid for deep pages

Put selective $match first, keep $sort next to $limit for top-N, and index the sort field when lists are hot.

Key Takeaways

  • Role: keep the first N documents; drop the rest.
  • Top-N: $sort then $limit.
  • Pages: $sort → $skip → $limit.
  • Reminder: limit alone does not define ranking.

One line: $limit answers “only keep the first N from here.”

Frequently Asked Questions

$limit passes only the first N documents from its input to the next stage and discards the rest. Use it to cap result size—top 10 after $sort, or one page of a paginated API.
{ $limit: <positive integer> }. Example: { $limit: 5 } returns at most five documents. If fewer than N documents arrive, you get all of them.
Yes for meaningful top-N (newest, highest score). Without $sort, $limit returns an arbitrary first N in pipeline order—rarely what you want for ranked lists.
Combine $skip and $limit after $sort. Page 1: skip 0, limit 20; page 2: skip 20, limit 20. For very large offsets, prefer cursor-based pagination over high $skip values.
$limit keeps the first N in current order. $sample picks N documents randomly. Use $limit for ranked or ordered slices; $sample for random subsets.
It can—especially with adjacent $sort + $limit (top-k) or after selective $match. Placing $limit early reduces work for later stages when ordering is already correct.

Next: $listLocalSessions

See active sessions on the current MongoDB server instance.

$listLocalSessions tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful