Beginner LevelMongoDB & Mongoose
How do sort(), limit(), and skip() work for cursor pagination?
❓ Interview Prompt: Explain cursor pagination methods: sort() (1 asc, -1 desc), limit(), skip(), and why range queries outperform offset skip().
MongoDB cursor methods control dataset pagination and ordering:
•
'sort({ createdAt: -1 })': Sorts results descending.
•
'limit(20)': Caps response count to 20 documents per page.
•
'skip(40)': Bypasses the first 40 matching documents.
Performance Warning: High 'skip()' offsets (e.g. 'skip(100000)') scan and discard thousands of index entries! Use Range-Based Cursor Pagination ('_id > lastId') for large datasets.
Code Implementation Example
typescript
import { ProductModel } from './models/Product';
// Range-Based Cursor Pagination (Fast & Scalable!)
async function getNextPage(lastSeenId?: string) {
const query = lastSeenId ? { _id: { $gt: lastSeenId } } : {};
return await ProductModel.find(query).sort({ _id: 1 }).limit(20);
}💡Implementing range-based cursor pagination avoiding expensive skip() offsets.
🎯 Interview Key Takeaway
Avoid large skip() offsets; use range-based cursor pagination (_id > lastId) for O(1) page performance.
#Pagination#sort#limit#skip#Beginner
Back to all MongoDB & Mongoose Questions→