MongoDB sorts query results with sort and paginates with limit and skip — chained on a find cursor. Together they handle ordering and returning pages of data, essential for displaying results.
MongoDB sorts query results with sort and paginates with limit and skip — chained on a find cursor. Together they handle ordering and returning pages of data, essential for displaying results.
db.users.find().sort({ age: 1 }); // ascending by age (1 = asc)
db.users.find().sort({ age: -1 }); // descending (-1 = desc)
db.users.find().sort({ country: 1, name: 1 }); // by country, then name (tie-break)
db.users.find().sort({ createdAt: -1 }); // newest first (common)
sort takes a document of field:direction (1 ascending, -1 descending). Multiple fields provide tie-breaking.
db.users.find().sort({ name: 1 }).limit(10); // first 10 (page 1)
db.users.find().sort({ name: 1 }).skip(10).limit(10); // skip 10, take 10 (page 2)
// page N: .skip((N-1) * pageSize).limit(pageSize)
limit(n) returns at most n documents; skip(m) skips the first m. Together they implement offset pagination (page N via skip + limit).
// ❌ pagination without sort → inconsistent order (pages may overlap/skip)
db.users.find().skip(10).limit(10);
// ✅ sort by a stable field for consistent pages
db.users.find().sort({ _id: 1 }).skip(10).limit(10);
Without sort, document order isn't guaranteed, so paginated pages can be inconsistent. Always sort by a stable field (like _id) when paginating.
// ⚠️ skip(1000000) must scan/skip a million docs → slow on deep pages
// ✅ range-based (cursor) pagination — far more efficient for large datasets
db.users.find({ _id: { $gt: lastSeenId } }).sort({ _id: 1 }).limit(10);
// → use the last document's _id to fetch the next page (uses the index, no skipping)
Sorting on an INDEXED field is efficient. Sorting a large result set WITHOUT an index
requires an in-memory sort (limited size — can fail/be slow for big sorts).
→ Index fields you sort by.
Sorting and pagination are fundamental for displaying data usefully in MongoDB — ordering results and returning manageable pages are near-universal needs (any list, feed, or table in an application), so understanding them is essential everyday knowledge.
Knowing sort (ordering by fields with 1/-1, with tie-breaking) and limit/skip (for offset pagination — returning pages of data) covers the common needs for presenting query results.
Two practical points are particularly important: always sort when paginating (without it, document order isn't guaranteed, causing inconsistent pages that overlap or skip documents — a real bug, the same issue as in SQL), and understanding that skip is slow on deep pages (it must scan and skip all preceding documents) — so range-based (cursor) pagination (using the last seen _id to fetch the next page, leveraging the index without skipping) is far more efficient for large datasets, a valuable performance technique.
Knowing that sorting on indexed fields is efficient while large unindexed sorts can be slow or fail (in-memory sort limits) is also important — index fields you sort by.
Since sorting and pagination are required for virtually any data display, and since the consistency requirement (sort for stable pagination) and performance considerations (skip vs range-based pagination, indexed sorts) directly affect correctness and speed, understanding MongoDB sorting and pagination — sort, offset pagination with skip/limit, the stable-sort requirement, the efficient range-based alternative, and indexing sort fields — is essential, frequently-applied knowledge for building applications that present MongoDB data effectively and performantly.