Sorting, Limiting, and Pagination
Retrieving data efficiently matters just as much as retrieving it correctly. This lesson covers sort(), limit(), and skip() — the trio that powers ordered results and pagination in MongoDB.
1. Sorting Results
// Sort ascending (1) by price
db.products.find().sort({ price: 1 })
// Sort descending (-1) by price
db.products.find().sort({ price: -1 })
// Sort by multiple fields
db.products.find().sort({ category: 1, price: -1 })
2. Limiting Results
// Return only the first 10 documents
db.products.find().limit(10)
// Combine sort and limit — top 5 most expensive products
db.products.find().sort({ price: -1 }).limit(5)
3. Skipping Results
// Skip the first 20 documents
db.products.find().skip(20)
// Pagination: page 3, 10 results per page
db.products.find().sort({ _id: 1 }).skip(20).limit(10)
| Page | skip() | limit() |
|---|---|---|
| Page 1 | 0 | 10 |
| Page 2 | 10 | 10 |
| Page 3 | 20 | 10 |
| Page N | (N-1) × pageSize | pageSize |
Performance Warning:
skip() becomes slow on large collections because MongoDB still has to scan and discard skipped documents. For deep pagination, prefer range-based (cursor) pagination instead.
4. Cursor-Based (Range) Pagination
Instead of skipping N documents, filter using the last seen _id — far more efficient at scale.
// First page
db.products.find().sort({ _id: 1 }).limit(10)
// Next page: use the last _id from the previous page
db.products.find({ _id: { $gt: lastSeenId } }).sort({ _id: 1 }).limit(10)
5. Sorting on Indexed Fields
Sorting is far more efficient when the sort field is indexed, since MongoDB can retrieve documents already in order instead of sorting them in memory.
db.products.createIndex({ price: -1 })
db.products.find().sort({ price: -1 }) // Uses the index — no in-memory sort
6. Pagination Checklist
- ✅ Understand sort(), limit(), and skip() individually
- ✅ Combine them correctly for classic offset pagination
- ✅ Know skip()'s performance cost on large datasets
- ✅ Implement cursor-based pagination for scale
- ✅ Index fields used for sorting
Key Takeaway: Offset pagination with skip() is fine for small datasets and admin UIs, but production-scale infinite scrolls and APIs should use cursor-based pagination for consistent performance.
Ready to master MongoDB?
Build real-world MongoDB-powered applications with hands-on projects, mentor-led sessions, and placement support.