Sorting documents returned by MongoDB query cursors in Node.js applications is configured using the .sort() method, passing direction values 1 for ascending or -1 for descending order.
flowchart LR
A["Raw Document Collection"] --> B["cursor.sort({ price: -1, title: 1 })"]
B --> C["Highest Price Documents First (Price DESC)"]
C --> D["Alphabetical Secondary Sort (Title ASC)"]
import { MongoClient } from 'mongodb';
const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri);
async function executeSortedQueries() {
try {
await client.connect();
const db = client.db('kodersolution_no_sql');
const products = db.collection('products');
// 1. Sort by single field descending (-1)
const highestPriceFirst = await products
.find({})
.sort({ price: -1 })
.toArray();
console.log('--- Highest Price Products ---');
highestPriceFirst.forEach(p => console.log(`$${p.price} - ${p.title}`));
// 2. Sort by multiple fields (category ASC, price DESC)
const multiSort = await products
.find({})
.sort({ category: 1, price: -1 })
.toArray();
console.log('--- Multi-Field Sorted Products ---');
multiSort.forEach(p => console.log(`[${p.category}] $${p.price} - ${p.title}`));
} catch (err) {
console.error('MongoDB Sort Error:', err.message);
} finally {
await client.close();
}
}
executeSortedQueries();
1 for ascending order and -1 for descending order in .sort({ field: 1 }).{ category: 1, price: -1 }) to avoid expensive 32MB in-memory sort caps..sort() before .limit().What values represent ascending and descending order in MongoDB .sort() specification objects?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.