Lesson

MongoDB Sort

10 min reading
Free Course

MongoDB Sort in Node.js: Ordering Results Efficiently

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).

Single and Multi-Field Sorting

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);

Avoiding the 32 MB In-Memory Sort Limit

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.

Common Mistakes to Avoid

  • Validating API ?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.
  • Relying on JavaScript object key order with numeric-looking field names: JavaScript moves integer-like object keys ("1", "2") to the front automatically; use an array of pairs ([['createdAt', -1], ['_id', -1]]) or clean field names.
  • Calling .sort() after .toArray(): .sort() is a FindCursor method, not an array method matching MongoDB syntax. Chain .find().sort().limit().toArray().

Frequently Asked Questions

Does the order of .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.

How does MongoDB sort strings case-insensitively?

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.

What does 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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
Node.js Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum