Skip to content

Results, Sorting & Pagination

limit() and skip()

Take a page of results — and why skip() is fine until the dataset is not.

BeginnerAbout 4 minutes

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)
Top 10 cheapest in-stock products
db.products
  .find({ inStock: true })
  .sort({ price: 1 })
  .skip(20)
  .limit(10)
Page 3 of 10 — skip 20, take 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()?

Think about it first.

Practice