Sorting MongoDB Documents using Node.js: Efficient Data Ordering

Learn how to sort documents in your MongoDB collections using Node.js. This tutorial provides practical examples demonstrating how to use the `sort()` method to order your data in ascending or descending order based on one or more fields, enhancing data retrieval and presentation.



Sorting MongoDB Documents with Node.js

This tutorial demonstrates how to sort documents in a MongoDB collection using Node.js. MongoDB's `sort()` method allows you to order your results in either ascending or descending order based on one or more fields.

Sorting in Ascending Order

To sort documents in ascending order, use a positive value (1) for the sort field:


db.collection('employees').find().sort({ name: 1 }).toArray(...)

This sorts documents in ascending order based on the value of the "name" field.

Example:


var MongoClient = require('mongodb').MongoClient;
// ... (database connection code) ...
db.collection('employees').find().sort({ name: 1 }).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
});

Sorting in Descending Order

To sort in descending order, use a negative value (-1):


db.collection('employees').find().sort({ name: -1 }).toArray(...)

This sorts documents in descending order based on the "name" field.

Example:


var MongoClient = require('mongodb').MongoClient;
// ... (database connection code) ...
db.collection('employees').find().sort({ name: -1 }).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
});