MongoDB sort(), skip() and limit() Explained (With Pagination Example)
Learn how to order query results with sort(), skip a number of documents with skip(), and cap results with limit() — the building blocks of MongoDB pagination.
sort(), skip() and limit()
These three cursor methods are usually chained together to page through query results.
sort()
Orders the returned documents by one or more fields. Use 1 for ascending, -1 for descending.
db.employees.find().sort({ age: 1 }) // ascending
db.employees.find().sort({ age: -1 }) // descending
db.employees.find().sort({ name: 1 })
skip()
Skips the first n documents in the result set — handy for pagination.
db.employees.find().skip(1) // skip the first document
db.employees.find().skip(2) // skip the first two
db.employees.find().skip(10) // returns nothing if fewer than 10 documents exist
limit()
Caps the number of documents returned, so your app isn't handed more data than it needs.
db.employees.find().limit(2)
db.employees.find({ city: "Palghar" }).limit(2)
Putting Them Together: Pagination
sort(), skip() and limit() combine to build classic "page 2 of results" style queries:
// page 2, 5 results per page, newest first
db.employees.find()
.sort({ doj: -1 })
.skip(5)
.limit(5)
Advertisement728 x 90
Common Errors & Troubleshooting
- Inconsistent pagination results without a sort —
skip()/limit()without ansort()don't guarantee a stable row order between calls; always pair them withsort()on a field with unique values (like_id) for reliable pagination. skip()getting slower as the page number grows — MongoDB still has to walk past every skipped document internally; for very deep pagination on huge collections, filter by the last-seen_idinstead of an ever-growingskip()value.- Sorting on an unindexed field at scale — sorting a huge collection without a supporting index can be slow and hit memory limits; add an index on the sort field for large collections (see the Indexing section).
Key Takeaways
sort()decides the order;skip()andlimit()decide the "window" of results.- These three methods chain directly off
find()and can be combined with a query filter too. - Together they're the standard recipe for pagination in MongoDB.
Advertisement320 x 100