Results, Sorting & Pagination
sort()
Ordering results, compound sorts, and how sort interacts with indexes.
find() does not promise order. sort() does. 1 is ascending, -1 is descending. Chain it on the cursor — same in the shell and in Node.
db.products.find({ inStock: true }).sort({ price: 1 }){ name: "USB-C Cable", price: 200, inStock: true }
{ name: "Mechanical Keyboard", price: 4500, inStock: true }db.orders.find({ status: "completed" }).sort({ createdAt: -1, _id: -1 })When two documents share createdAt, the next key breaks the tie. Pagination later depends on a stable unique sort — _id is the usual tiebreaker. A sort that does not fit in memory used to fail past 32MB (it can spill to disk now, but an in-memory sort of a huge result is still the wrong design). An index that matches the sort (Indexing module) is how production avoids that.
Interview question
How does sort() work, and why include _id in a compound sort?
sort({ field: 1 }) or -1 for descending. Several fields are applied left to right. A unique last key such as _id makes the order stable when the interesting fields tie — required for cursor pagination.
Practice
Sort and limit on the products collection.