QA
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→

More MongoDB & Mongoose Interview Questions

Beginner LevelMongoDB & Mongoose

How does the MongoDB Aggregation Pipeline work? Explain $match, $group, $lookup, and $project.

Beginner LevelMongoDB & Mongoose

What is MongoDB and how does the BSON document data model work?

Beginner LevelMongoDB & Mongoose

What is the structure of a MongoDB ObjectId and how is it generated?