- Node.js Tutorial
- NodeJS Home
- NodeJS Introduction
- NodeJS Setup
- NodeJS First App
- NodeJS REPL
- NodeJS Command Line
- NodeJS NPM
- NodeJS Callbacks
- NodeJS Events
- NodeJS Event-Loop
- NodeJS Event-Emitter
- NodeJS Global-Objects
- NodeJS Console
- NodeJS Process
- NodeJS Buffers
- NodeJS Streams
- Node.js File Handling
- Node.js File System
- Node.js Read/Write File
- Working with folders in Node.js
- HTTP and Networking
- Node.js HTTP Module
- Anatomy of an HTTP Transaction
- Node.js MongoDB
- MongoDB Get Started
- MongoDB Create Database
- MongoDB Create Collection
- MongoDB Insert
- MongoDB Find
- MongoDB Query
- MongoDB Sort
- MongoDB Delete
- MongoDB Update
- MongoDB Limit
- MongoDB Join
- Node.js MySQL
- MySQL Get Started
- MySQL Create Database
- MySQL Create Table
- MySQL Insert Into
- MySQL Select From
- MySQL Where
- MySQL Order By
- MySQL Delete
- MySQL Update
- MySQL Join
- Node.js Modules
- Node.js Modules
- Node.js Built-in Modules
- Node.js Utility Modules
- Node.js Web Module
- Node.js Advanced
- Node.js Debugger
- Node.js Scaling Application
- Node.js Packaging
- Node.js Express Framework
- Node.js RESTFul API
- Node.js Useful Resources
- Node.js Useful Resources
- Node.js Discussion
Node.js MongoDB Sort
Sorting is a fundamental operation in database management that allows you to organize query results in a way that makes sense for your application—whether you're building a leaderboard, a chronological feed, or an alphabetical directory. When using Node.js with the official mongodb driver, sorting is performed on the server side, ensuring that your application receives data that is already ordered and ready for display.
Key Features of MongoDB Sort
- Directional Sorting: You can control the order of data using integers:
1for ascending (A-Z, 0-9) and-1for descending (Z-A, 9-0). - Multi-Level Sorting: MongoDB allows you to define a sequence of fields to sort by. If two documents have the same value in the first field, the database uses the second field as a "tie-breaker."
- Performance Optimization: By using indexes on sorted fields, MongoDB can return ordered results almost instantaneously without scanning every document in the collection.
.sort() method.
Step 1 Prerequisites
Before you begin, ensure you have a Node.js environment set up and a running MongoDB instance (local or Atlas). You will need the official MongoDB driver installed in your project directory.
npm install mongodb
Step 2 Basic Sorting
To sort documents, we chain the .sort() method to a .find() query. The sort() method takes an object where the key is the field name and the value is the direction (1 for ascending).
Example Code
const { MongoClient } = require('mongodb');
// Connection URL and Database Name
const url = 'mongodb://127.0.0.1:27017';
const dbName = 'mydatabase';
async function sortExample() {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Sort by age in ascending order (youngest to oldest)
const result = await collection.find().sort({ age: 1 }).toArray();
console.log('Sorted by Age (Ascending):', result);
} finally {
await client.close();
}
}
sortExample().catch(console.error);
Output:
[
{ "_id": 1, "name": "Alice", "age": 25 },
{ "_id": 2, "name": "Bob", "age": 30 },
{ "_id": 3, "name": "Charlie", "age": 35 }
]
Step 3 Descending Sorting
Descending order (-1) is commonly used for "Newest First" logic or finding the highest values in a set, such as the most recent blog posts or the highest-spending customers.
Example Code
async function sortDescending() {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Sort by age in descending order (oldest to youngest)
const result = await collection.find().sort({ age: -1 }).toArray();
console.log('Sorted by Age (Descending):', result);
} finally {
await client.close();
}
}
sortDescending().catch(console.error);
Output:
[
{ "_id": 3, "name": "Charlie", "age": 35 },
{ "_id": 2, "name": "Bob", "age": 30 },
{ "_id": 1, "name": "Alice", "age": 25 }
]
sort({ createdAt: -1 }). If you haven't defined a createdAt field, you can technically sort by the _id field in descending order, as MongoDB ObjectIDs contain a timestamp.
Step 4 Sorting by Multiple Fields
In many real-world scenarios, one sort criteria isn't enough. For example, if you have many users with the same age, you might want to sort those specific users alphabetically by their name.
Example Code
async function sortByMultipleFields() {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Primary sort: age (ascending). Secondary sort: name (descending).
const result = await collection.find().sort({ age: 1, name: -1 }).toArray();
console.log('Sorted by Age (Ascending) and Name (Descending):', result);
} finally {
await client.close();
}
}
sortByMultipleFields().catch(console.error);
Output:
[
{ "_id": 1, "name": "Alice", "age": 25 },
{ "_id": 2, "name": "Bob", "age": 30 },
{ "_id": 3, "name": "Charlie", "age": 35 }
]
{ age: 1, name: 1 } is not the same as { name: 1, age: 1 }. The database processes the first key first, then uses the second key only to resolve ties.
Step 5 Limit and Sort Combined
The combination of sort() and limit() is the standard way to create "Top 10" lists, "Latest News," or "Featured Products." By sorting first and then limiting, you ensure you are getting the specific subset of data you need rather than just the first few items the database finds.
Example Code
async function sortAndLimit() {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Real-world use case: Get the 2 oldest users
const result = await collection.find().sort({ age: -1 }).limit(2).toArray();
console.log('Top 2 Users by Age:', result);
} finally {
await client.close();
}
}
sortAndLimit().catch(console.error);
Output:
[
{ "_id": 3, "name": "Charlie", "age": 35 },
{ "_id": 2, "name": "Bob", "age": 30 }
]
sort() in conjunction with skip() and limit(). Without a defined sort order, the items on page 2 might overlap with page 1 if the natural order of the database changes.
Summary
Sorting in MongoDB with Node.js is a powerful way to organize your data directly on the server. By mastering the 1 and -1 modifiers, multi-field sorting, and combining queries with limit(), you can build efficient and user-friendly data displays. Remember to always consider indexing for performance and handle case sensitivity if your application requires specific text ordering.