
Mongodb Sort in NodeJs
Sorting data in MongoDB with Node.js is really easy β and works great whether you're using the native MongoDB driver or Mongoose.
Letβs look at both approaches π
β 1. Using the Native MongoDB Driver
π¦ Step 1: Install the Driver
npm install mongodb
π Step 2: Use .sort()
in a Query
const { MongoClient } = require('mongodb');const uri = 'mongodb://localhost:27017';const client = new MongoClient(uri);async function sortUsers() { try { await client.connect(); const db = client.db('myDatabase'); const users = db.collection('users'); // Sort by age ascending const ascending = await users.find().sort({ age: 1 }).toArray(); console.log('Age Ascending:', ascending); // Sort by name descending const descending = await users.find().sort({ name: -1 }).toArray(); console.log('Name Descending:', descending); } catch (err) { console.error(err); } finally { await client.close(); }}sortUsers();
πͺ 2. Using Mongoose
π¦ Step 1: Install Mongoose
npm install mongoose
π Step 2: Use .sort()
with Mongoose
const mongoose = require('mongoose');mongoose.connect('mongodb://localhost:27017/myDatabase') .then(() => console.log('Connected'));const userSchema = new mongoose.Schema({ name: String, age: Number });const User = mongoose.model('User', userSchema);async function sortWithMongoose() { // Sort by age (ascending) const ageAsc = await User.find().sort({ age: 1 }); // Sort by name (descending) const nameDesc = await User.find().sort({ name: -1 }); console.log('Age Asc:', ageAsc); console.log('Name Desc:', nameDesc); mongoose.disconnect();}sortWithMongoose();
π Sorting Syntax
Expression | Meaning |
---|---|
{ field: 1 } | Sort by field ascending |
{ field: -1 } | Sort by field descending |
.sort({ age: 1, name: -1 }) | Sort by age asc, then name desc |
π§ Combine with .limit()
or .skip()
for Pagination
Example:
User.find().sort({ age: -1 }).skip(10).limit(5);