Sorting Limiting Pagination
When you have hundreds or thousands of documents, you don't want to see them all at once. You want to sort them in a specific order, limit the number you see, and paginate through them. MongoDB provides powerful methods for this: `sort()`, `limit()`, and `skip()`.
Sorting Results with sort()
The `sort()` method allows you to sort documents in ascending or descending order based on one or more fields.
<!-- Sort by price ascending (1 = ascending) -->db.products.find().sort({ price: 1 }).pretty()
<!-- Sort by price descending (-1 = descending) -->db.products.find().sort({ price: -1 }).pretty()
<!-- Sort by category ascending, then price descending -->db.products.find().sort({ category: 1, price: -1 }).pretty()Think of `sort()` like organizing a deck of cards. You can sort by suit (ascending) and then by rank (descending) – exactly like MongoDB sorts documents.
Limiting Results with limit()
The `limit()` method restricts the number of documents returned. This is essential for performance and user experience.
<!-- Get only the first 5 products -->db.products.find().limit(5).pretty()
<!-- Get the 5 cheapest products -->db.products.find().sort({ price: 1 }).limit(5).pretty()Skipping Results with skip()
The `skip()` method ignores the first N documents. This is used for pagination – to get the second page of results.
<!-- Skip the first 5 products, then show the next 5 -->db.products.find().skip(5).limit(5).pretty()Building Pagination
Pagination is a common pattern in web applications. You show 10 items per page, and users can click "Next" to see more.
<!-- Page 1: items 1-10 -->db.products.find().sort({ createdAt: -1 }).limit(10).pretty()
<!-- Page 2: items 11-20 -->db.products.find().sort({ createdAt: -1 }).skip(10).limit(10).pretty()
<!-- Page 3: items 21-30 -->db.products.find().sort({ createdAt: -1 }).skip(20).limit(10).pretty()Practical Example: E-commerce Product Listing
<!-- Insert sample products -->db.products.insertMany([ { name: "Laptop", price: 999, category: "electronics", inStock: true }, { name: "Mouse", price: 25, category: "electronics", inStock: true }, { name: "Book", price: 15, category: "books", inStock: true }, { name: "Headphones", price: 50, category: "electronics", inStock: false }, { name: "Desk", price: 200, category: "furniture", inStock: true }, { name: "Chair", price: 150, category: "furniture", inStock: true }, { name: "Notebook", price: 5, category: "books", inStock: true }, { name: "Pen", price: 2, category: "books", inStock: true }, { name: "Monitor", price: 300, category: "electronics", inStock: true }, { name: "Keyboard", price: 75, category: "electronics", inStock: true }])
<!-- Show 5 cheapest in-stock products -->db.products.find( { inStock: true }).sort({ price: 1 }).limit(5).pretty()
<!-- Electronics page 1: first 3 electronics items -->db.products.find( { category: "electronics" }).limit(3).pretty()
<!-- Electronics page 2: next 3 electronics items -->db.products.find( { category: "electronics" }).skip(3).limit(3).pretty()Counting Total Pages
To build a proper pagination UI, you need to know the total number of pages:
const pageSize = 10;const totalProducts = db.products.countDocuments({ category: "electronics" });const totalPages = Math.ceil(totalProducts / pageSize);
console.log(`Total pages: ${totalPages}`);Important Notes
- Order matters: `sort()` then `skip()` then `limit()` – MongoDB applies them in this order.
- Performance: Skipping many documents can be slow. For large datasets, consider using range-based pagination with `_id` or indexed fields.
Two Minute Drill
- `sort({ field: 1 })` for ascending, `sort({ field: -1 })` for descending.
- `limit(n)` restricts results to n documents.
- `skip(n)` ignores the first n documents.
- Combine all three for pagination: `sort().skip().limit()`.
- Always use `sort()` with pagination to ensure consistent order between pages.
Need more clarification?
Drop us an email at career@quipoinfotech.com
