ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Mongodb Sort in NodeJs

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='22' AND `tutorial_submenu`='1404' AND `tutorial_status`=1 LIMIT 1

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

bash

npm install mongodb


πŸ”„ Step 2: Use .sort() in a Query

js

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

bash

npm install mongoose


πŸ”„ Step 2: Use .sort() with Mongoose

js

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

ExpressionMeaning
{ 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:

js

User.find().sort({ age: -1 }).skip(10).limit(5);

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql