π The Tale of the Library Search Master
Imagine managing a library with 1 million books. A student asks: "Show me programming books from 2020+, over 300 pages, authors starting with 'J', in English or Spanish."
Without sorting & pagination: Manually check all 1 million books β Takes YEARS!
With MongoDB: Get exactly 23 matching books in 0.5 seconds! β¨
π€ Sorting Examples
Example 1: Sort by Age (Ascending)
db.users.find().sort({ age: 1 })
// Returns: youngest β oldest
Example 2: Sort by Name (Descending)
db.users.find().sort({ name: -1 })
// Returns: Z β A alphabetically
Example 3: Multiple Field Sort
db.users.find().sort({ city: 1, age: -1 })
// Sort by city (AβZ), then age (oldβyoung) within each city
π‘ Pro Tip:
Always create indexes on fields you sort frequently for better performance!
π Pagination Examples
Example 1: First Page (10 items)
db.products.find().limit(10)
// Shows items 1-10
Example 2: Second Page
db.products.find().skip(10).limit(10)
// Shows items 11-20
Example 3: Calculate Skip for Any Page
const page = 5;
const pageSize = 10;
const skip = (page - 1) * pageSize;
db.products.find().skip(skip).limit(pageSize)
// Page 5 β skip 40, show 10 (items 41-50)
β Performance Warning:
skip() is slow for large offsets. For deep pagination, use cursor-based pagination instead!
π― Combining Sort + Pagination
The most powerful pattern combines filtering, sorting, and pagination:
// Get page 2 of premium users, sorted by age
db.users
.find({ premium: true }) // Filter
.sort({ age: -1 }) // Sort
.skip(10) // Skip page 1
.limit(10) // Page size
// Real e-commerce example
db.products
.find({
category: "electronics",
price: { $lte: 1000 }
})
.sort({ rating: -1, price: 1 }) // Best rated, then cheapest
.skip(20)
.limit(10)