Node.js MongoDB Sorting

In MongoDB, the sort() method is used for sorting the results in ascending or descending order. The sort() method uses a parameter to define the object sorting order.

Value used for sorting in ascending order:  

{ name: 1 }  

Value used for sorting in descending order:  

{ name: -1 }

Sort in Ascending Order

Example

Sort the records in ascending order by the name.

Create a js file named “sortasc.js”, having the following code:PlayNextMute

Current Time 0:00

/

Duration 18:10

Loaded: 2.94%

 Fullscreen

var http = require('http');  

var MongoClient = require('mongodb').MongoClient;  

var url = "mongodb://localhost:27017/ MongoDatabase";  

MongoClient.connect(url, function(err, db) {  

if (err) throw err;  

var mysort = { name: 1 };  

db.collection("employees").find().sort(mysort).toArray(function(err, result) {  

if (err) throw err;  

console.log(result);  

db.close();  

});  

});

Open the command terminal and run the following command:

Node sortasc.js  
Node.js Sorting 1

Sort in Descending Order

Example

Sort the records in descending order according to name:

Create a js file named “sortdsc.js”, having the following code:

var http = require('http');  

var MongoClient = require('mongodb').MongoClient;  

var url = "mongodb://localhost:27017/ MongoDatabase";  

MongoClient.connect(url, function(err, db) {  

if (err) throw err;  

var mysort = { name: -1 };  

db.collection("employees").find().sort(mysort).toArray(function(err, result) {  

if (err) throw err;  

console.log(result);  

db.close();  

});  

});

Open the command terminal and run the following command:

Node sortdsc.js  
Node.js Sorting 2

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *