How to Use Skip in MongoDB for Pagination and Data Skipping
In MongoDB, use the
skip() method to skip a specified number of documents in the query result. This is useful for pagination or ignoring a set of documents before returning results. Combine skip() with limit() to control the number of documents returned after skipping.Syntax
The skip() method takes one argument: the number of documents to skip in the query result.
number: The count of documents to skip.
It is usually chained after a find() query.
mongodb
db.collection.find(query).skip(numberToSkip)
Example
This example shows how to skip the first 3 documents in the users collection and return the next 2 documents.
mongodb
db.users.find().skip(3).limit(2)
Output
[
{ "_id": 4, "name": "Alice" },
{ "_id": 5, "name": "Bob" }
]
Common Pitfalls
One common mistake is using skip() without limit(), which can return a large number of documents and affect performance. Another issue is skipping too many documents in large collections, which can be slow because MongoDB still scans those documents internally.
Also, skip() does not guarantee consistent results if the data changes between queries, so use it carefully for pagination.
mongodb
/* Wrong: Skipping without limit may return many documents */ db.users.find().skip(1000) /* Right: Use skip with limit for pagination */ db.users.find().skip(1000).limit(10)
Quick Reference
| Method | Description | Example |
|---|---|---|
| find() | Selects documents | db.collection.find({}) |
| skip(n) | Skips first n documents | db.collection.find().skip(5) |
| limit(n) | Limits result to n documents | db.collection.find().limit(10) |
| skip + limit | Skip then limit for pagination | db.collection.find().skip(10).limit(5) |
Key Takeaways
Use
skip(n) to skip the first n documents in a MongoDB query result.Combine
skip() with limit() to paginate results efficiently.Avoid skipping large numbers of documents in big collections to prevent slow queries.
Skipping documents does not guarantee stable pagination if data changes between queries.
Always test queries with skip to ensure performance and expected results.