Node.js MongoDB Sort
✅ Node.js MongoDB Sort
Sorting in MongoDB is done using the .sort() method.
It works with:
-
1→ Ascending (A → Z / Small → Large) -
-1→ Descending (Z → A / Large → Small)
You can use sort with any find() query.
⭐ 1. Sort Ascending
Sort customers by name (A–Z)
⭐ 2. Sort Descending
Sort customers by name (Z–A)
⭐ 3. Sort by Multiple Fields
Sort by city ASC, then age DESC
This means:
-
First sort by city A → Z
-
If two documents have same city, sort them by age high → low
⭐ 4. Sort with Query Filters
Example: Find all customers in Surat and sort by age descending.
⭐ 5. Sort with Limit
Example: Get top 5 oldest customers.
