MongoDB sorts query results on the server using .sort() chained onto a FindCursor before calling .toArray(). Pass 1 for ascending order (A → Z, 0 → 9, oldest → newest) and -1 for descending order (Z → A, 9 → 0, newest → oldest).
When sorting by multiple fields, pass keys in priority order. Always include _id as a final tie-breaker so pagination never skips or duplicates documents that share identical timestamps or prices.
import { MongoClient } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017');
async function getSortedOrders() {
try {
await client.connect();
const orders = client.db('kodersolution_store').collection('orders');
// Sort highest priority first, then newest, then _id tie-breaker
const results = await orders
.find({ status: 'paid' })
.sort({ priority: -1, createdAt: -1, _id: -1 })
.limit(20)
.toArray();
console.log('Sorted orders count:', results.length);
} finally {
await client.close();
}
}
getSortedOrders().catch(console.error);
If no index matches your .sort() fields, MongoDB loads matching documents into memory to sort them and throws an error once the sort buffer exceeds 32 MB (or 100 MB in newer servers). Creating a compound index matching your filter and sort order (createIndex({ status: 1, createdAt: -1 })) lets MongoDB stream results pre-sorted directly from the index.
?sort= parameters carelessly: Allowing users to pass arbitrary objects directly into .sort(req.query.sort) lets clients trigger slow unindexed sorts across massive collections. Map allowed sort presets in code instead."1", "2") to the front automatically; use an array of pairs ([['createdAt', -1], ['_id', -1]]) or clean field names..sort() after .toArray(): .sort() is a FindCursor method, not an array method matching MongoDB syntax. Chain .find().sort().limit().toArray()..sort() and .limit() matter on a MongoDB cursor?No. MongoDB's query planner always applies filtering first, then .sort(), and finally .skip() and .limit() regardless of the order you chain them on the cursor.
By default, MongoDB sorts strings by UTF-8 byte order ("Z" before "a"). Pass .collation({ locale: 'en', strength: 2 }) on the query (and matching index) for natural case-insensitive sorting.
allowDiskUse(true) do?Chaining .allowDiskUse(true) lets MongoDB spill large unindexed sorts to temporary disk files instead of failing when exceeding RAM limits, though adding a proper index is always faster.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.