Skip to content

Results, Sorting & Pagination

sort()

Ordering results, compound sorts, and how sort interacts with indexes.

BeginnerAbout 4 minutes

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 })
Cheapest products first
{ 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 })
Compound sort: newest orders first; same timestamp → _id

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?

Think about it first.

Practice

Sort and limit on the products collection.