0
0
MongodbHow-ToBeginner · 4 min read

How to Use Sort in Mongoose: Syntax and Examples

In Mongoose, you use the sort() method on a query to order documents by one or more fields. Pass an object to sort() where keys are field names and values are 1 for ascending or -1 for descending order.
📐

Syntax

The sort() method takes an object where each key is a field name and the value is either 1 for ascending order or -1 for descending order.

You can sort by multiple fields by adding more key-value pairs.

javascript
Model.find().sort({ field1: 1, field2: -1 })
💻

Example

This example shows how to sort users by their age in ascending order and then by name in descending order.

javascript
const mongoose = require('mongoose');

// Define a simple User schema
const userSchema = new mongoose.Schema({
  name: String,
  age: Number
});

const User = mongoose.model('User', userSchema);

async function run() {
  await mongoose.connect('mongodb://localhost:27017/testdb');

  // Clear existing users
  await User.deleteMany({});

  // Add sample users
  await User.insertMany([
    { name: 'Alice', age: 30 },
    { name: 'Bob', age: 25 },
    { name: 'Charlie', age: 30 },
    { name: 'David', age: 25 }
  ]);

  // Find users sorted by age ascending, then name descending
  const users = await User.find().sort({ age: 1, name: -1 });

  console.log(users.map(u => ({ name: u.name, age: u.age })));

  await mongoose.disconnect();
}

run();
Output
[ { name: 'David', age: 25 }, { name: 'Bob', age: 25 }, { name: 'Charlie', age: 30 }, { name: 'Alice', age: 30 } ]
⚠️

Common Pitfalls

  • Passing a string like sort('age') sorts ascending by default, but using an object is clearer.
  • Using sort({ age: 'asc' }) works but is less common than 1 and -1.
  • For descending order, do not use sort({ age: desc }) without quotes around 'desc' as a string; it must be a string, not a variable.
  • Remember to call sort() before exec() or await the query.
javascript
/* Wrong way: passing a string with direction as variable (won't work) */
// const direction = desc;
// Model.find().sort({ age: direction }); // Error: desc is not defined

/* Right way: use string or number */
Model.find().sort({ age: 'desc' });
Model.find().sort({ age: -1 });
📊

Quick Reference

UsageDescription
sort({ field: 1 })Sort by field ascending
sort({ field: -1 })Sort by field descending
sort({ field1: 1, field2: -1 })Sort by multiple fields
sort('field')Sort by field ascending (string shorthand)
sort({ field: 'asc' })Sort ascending using string (less common)
sort({ field: 'desc' })Sort descending using string

Key Takeaways

Use sort({ field: 1 }) for ascending and sort({ field: -1 }) for descending order in Mongoose queries.
You can sort by multiple fields by passing multiple key-value pairs to sort().
Always call sort() before executing the query with exec() or await.
Avoid passing undefined variables as sort directions; use 1, -1, 'asc', or 'desc' strings.
Using an object with sort() is clearer and more flexible than string shorthand.