How to Paginate Results in MongoDB: Simple Guide
To paginate results in MongoDB, use the
skip() method to skip a number of documents and limit() to restrict the number of documents returned. This combination lets you fetch results page by page efficiently.Syntax
Pagination in MongoDB uses two main methods on a query: skip(n) and limit(m).
skip(n): Skips the firstndocuments in the result set.limit(m): Limits the result tomdocuments.
Use them together to get a specific page of results.
mongodb
db.collection.find().skip(n).limit(m)
Example
This example shows how to get the second page of results with 3 documents per page from a collection named products.
javascript
const page = 2; const pageSize = 3; const results = db.products.find() .skip((page - 1) * pageSize) .limit(pageSize) .toArray(); printjson(results);
Output
[
{ "_id": 4, "name": "Product D", "price": 40 },
{ "_id": 5, "name": "Product E", "price": 50 },
{ "_id": 6, "name": "Product F", "price": 60 }
]
Common Pitfalls
Common mistakes when paginating in MongoDB include:
- Using
skip()with very large numbers causes slow queries because MongoDB must scan skipped documents. - Not sorting results before paginating can lead to inconsistent pages.
- Assuming
skip()andlimit()work well for very large datasets without optimization.
To fix these, always use sort() before paginating and consider using range queries or indexed fields for large collections.
mongodb
/* Wrong: No sort, large skip */ db.products.find().skip(10000).limit(10); /* Right: Sort by _id before paginating */ db.products.find().sort({_id: 1}).skip(10000).limit(10);
Quick Reference
| Method | Description | Example |
|---|---|---|
| skip(n) | Skips first n documents | skip(10) |
| limit(m) | Limits result to m documents | limit(5) |
| sort(criteria) | Sorts documents by criteria | sort({_id: 1}) |
Key Takeaways
Use skip() and limit() together to paginate MongoDB query results.
Always sort results before paginating to ensure consistent order.
Avoid large skip values on big collections to prevent slow queries.
Consider range queries or indexed fields for efficient large-scale pagination.