0
0
MongoDBquery~10 mins

$limit and $skip stages in MongoDB - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - $limit and $skip stages
Start with full dataset
Apply $skip: remove first N documents
Apply $limit: keep only next M documents
Output the resulting documents
The data flows first through $skip which removes a number of documents from the start, then through $limit which keeps only a set number of documents after skipping.
Execution Sample
MongoDB
db.collection.aggregate([
  { $skip: 2 },
  { $limit: 3 }
])
This query skips the first 2 documents and then returns the next 3 documents from the collection.
Execution Table
StepInput Documents$skip AppliedDocuments After $skip$limit AppliedDocuments After $limit
1[D1, D2, D3, D4, D5, D6]Skip 2[D3, D4, D5, D6]Limit 3[D3, D4, D5]
2[D3, D4, D5, D6]Skip 2 (already done)[D3, D4, D5, D6]Limit 3 (already done)[D3, D4, D5]
ExitNo more stagesN/AN/AN/AFinal output: [D3, D4, D5]
💡 After skipping 2 documents, limit keeps only 3 documents, so output is [D3, D4, D5].
Variable Tracker
VariableStartAfter $skipAfter $limit
Documents[D1, D2, D3, D4, D5, D6][D3, D4, D5, D6][D3, D4, D5]
Key Moments - 2 Insights
Why does $skip remove documents before $limit selects them?
Because in the execution_table, $skip is applied first (Step 1), reducing the dataset before $limit chooses how many to keep.
What happens if $limit is larger than the remaining documents after $skip?
The output will include all remaining documents after $skip.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 1, what documents remain after applying $skip?
A[D1, D2]
B[D3, D4, D5, D6]
C[D3, D4, D5]
D[D4, D5, D6]
💡 Hint
Check the 'Documents After $skip' column in Step 1 of execution_table.
At which step does the $limit stage reduce the documents to 3?
AExit
BStep 2
CStep 1
DBefore Step 1
💡 Hint
Look at the 'Documents After $limit' column in Step 1 of execution_table.
If we change $skip to 3, how many documents will remain after $skip?
A3
B4
C2
D6
💡 Hint
Original dataset has 6 documents; skipping 3 removes first 3, so 3 remain.
Concept Snapshot
$skip and $limit stages in MongoDB aggregation:
- $skip N: skips first N documents
- $limit M: limits output to M documents
- Order matters: $skip runs before $limit
- Use to paginate or slice data
- Syntax: [{ $skip: N }, { $limit: M }]
Full Transcript
This visual execution shows how MongoDB aggregation stages $skip and $limit work together. Starting with a dataset of 6 documents, $skip removes the first 2 documents, leaving 4. Then $limit keeps only the next 3 documents. The final output is 3 documents after skipping 2. Variables track the documents at each stage. Key moments clarify why order matters and what happens if limits exceed remaining documents. Quizzes test understanding of the steps and effects of changing skip values.