Keyset Pagination With Range Queries
Learners will build cursor-based pagination using a range filter on _id or a timestamp field, achieving consistent O(log n) page performance.
What Is Keyset Pagination?
Keyset pagination—also called cursor pagination—avoids skip() entirely by using a range query on the sort key. Instead of telling MongoDB 'jump over the first N documents', you tell it 'give me documents where the sort key is greater than the last value I saw'. This is always O(log n) because it uses an index range scan, regardless of how far into the result set you are.
The Core Concept: A Range Filter as a Cursor
After fetching the first page, you remember the sort key value of the last document returned. For the next page, you filter documents where the sort key is strictly greater than (or less than, for descending) that remembered value. This filter combined with an index gives MongoDB an exact starting point—no skipping needed.
// First page — no cursor needed
const page1 = await db.collection('posts')
.find({ isPublished: true })
.sort({ createdAt: -1, _id: -1 })
.limit(20)
.toArray();
// Remember the last document's sort keys
const lastCreatedAt = page1[page1.length - 1].createdAt;
const lastId = page1[page1.length - 1]._id;All lessons in this course
- Sorting With sort() and Multiple Keys
- Skip and Limit: Offset Pagination
- Keyset Pagination With Range Queries
- Combining Sort, Skip, Limit, and Projections