$limit and $skip stages in MongoDB - Time & Space Complexity
When using MongoDB, it's important to know how stages like $limit and $skip affect the work the database does.
We want to understand how the time to get results changes as we ask for more or skip more documents.
Analyze the time complexity of the following code snippet.
db.collection.aggregate([
{ $skip: 100 },
{ $limit: 50 }
])
This pipeline skips the first 100 documents and then returns the next 50 documents from the collection.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning documents to skip and then to limit.
- How many times: The database reads documents up to the number skipped plus the number limited.
As the number of documents to skip and limit grows, the work grows roughly by adding those two numbers.
| Input Size (skip + limit) | Approx. Operations |
|---|---|
| 10 + 5 = 15 | About 15 document reads |
| 100 + 50 = 150 | About 150 document reads |
| 1000 + 500 = 1500 | About 1500 document reads |
Pattern observation: The work grows linearly with the total number of documents skipped and limited.
Time Complexity: O(skip + limit)
This means the time to get results grows in a straight line as you increase how many documents you skip plus how many you want to return.
[X] Wrong: "Skipping documents is free and does not affect performance."
[OK] Correct: The database still has to read and count each skipped document, so skipping many documents takes more time.
Understanding how $skip and $limit affect performance helps you explain how queries scale and how to handle large data sets efficiently.
"What if we replaced $skip with a range query filter? How would the time complexity change?"