Results, Sorting & Pagination
limit() and skip()
Take a page of results — and why skip() is fine until the dataset is not.
limit(n) stops after n documents. skip(n) discards the first n, then continues. Together they look like OFFSET / LIMIT in SQL. That is page 1. That is also how people accidentally scan half a collection.
db.products
.find({ inStock: true })
.sort({ price: 1 })
.limit(10)db.products
.find({ inStock: true })
.sort({ price: 1 })
.skip(20)
.limit(10)skip(20) is cheap. skip(200000) is not: the server still walks 200,000 index (or collection) entries and throws them away. Offset pagination and the performance lesson make that concrete. For now: always sort before you skip, or 'page 2' is a random 10.
Interview question
What do limit() and skip() do, and what is the catch with skip()?
limit caps how many documents come back. skip drops that many first. skip(n) still has to walk n documents (or index keys), so large offsets get slower. I always sort if the page must be meaningful.
Practice