Pagination pattern with skip and limit in MongoDB - Time & Space Complexity
When using pagination in MongoDB, we often use skip and limit to get a portion of data.
We want to understand how the time to get results changes as we ask for pages further down the list.
Analyze the time complexity of the following code snippet.
db.collection.find().skip(1000).limit(10)
This code skips the first 1000 documents and then returns the next 10 documents from the collection.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Skipping over documents before returning the page.
- How many times: The database must scan or traverse each document up to the skip number (e.g., 1000 times).
As the skip number grows, the database does more work to reach the starting point of the page.
| Input Size (skip n) | Approx. Operations |
|---|---|
| 10 | About 10 document scans |
| 100 | About 100 document scans |
| 1000 | About 1000 document scans |
Pattern observation: The work grows roughly in direct proportion to the skip value.
Time Complexity: O(n)
This means the time to get a page grows linearly with how many documents you skip.
[X] Wrong: "Skipping documents is instant and does not affect performance."
[OK] Correct: The database must still look at each skipped document internally, so skipping many documents takes more time.
Understanding how pagination works under the hood helps you explain trade-offs and choose better methods in real projects.
"What if we replaced skip with a range query on an indexed field? How would the time complexity change?"