sort() orders the documents in the result set before they are returned. You pass a document specifying one or more fields and their sort direction.
Direction Values
| Value | Direction | Examples |
|---|---|---|
1 | Ascending | A→Z, 0→9, oldest→newest |
-1 | Descending | Z→A, 9→0, newest→oldest |
Single-Field Sort
// Cheapest products first (ascending price) db.products.find({}).sort({ price: 1 }) // Newest orders first (descending createdAt) db.orders.find({}).sort({ createdAt: -1 }) // Natural insertion order (ascending _id ≈ insertion order for ObjectId) db.logs.find({}).sort({ _id: 1 })
Compound Sort
Multiple fields are applied left to right. MongoDB sorts by the first field, then uses subsequent fields to break ties.
// Sort by category ascending, then by price descending within each category db.products.find({}).sort({ category: 1, price: -1 }) // Sort by score descending, then by name ascending for players with equal scores db.leaderboard.find({}).sort({ score: -1, name: 1 })
Sorting with Dates and Strings
// Dates sort chronologically when stored as ISODate db.events.find({}).sort({ date: 1 }) // earliest first // Strings sort lexicographically (dictionary order, case-sensitive by default) // "Apple" < "banana" because uppercase letters have lower code points than lowercase db.words.find({}).sort({ word: 1 }) // Numbers stored as numbers sort numerically — as expected // Numbers stored as STRINGS sort lexicographically: "200" < "30" (see edge cases)
allowDiskUse() for Large Sorts
// MongoDB has a 100MB memory limit for sort operations // For very large result sets that exceed this limit, use allowDiskUse() db.bigCollection.find({}).sort({ field: 1 }).allowDiskUse() // Without allowDiskUse(), MongoDB throws: // "Sort exceeded memory limit of 104857600 bytes"
allowDiskUse() spills sort data to temporary disk files, which is slower than in-memory sorting. The real fix is to add an index on the sort field so the sort is satisfied by index order and no in-memory sort is needed at all.