Dark Mode
Image

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.

  1. Value used for sorting in ascending order:  
  2. { name: 1 }  
  3. Value used for sorting in descending order:  
  4. { 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:

Advertisement.

  1. var http = require('http');  
  2. var MongoClient = require('mongodb').MongoClient;  
  3. var url = "mongodb://localhost:27017/ MongoDatabase";  
  4. MongoClient.connect(url, function(err, db) {  
  5. if (err) throw err;  
  6. var mysort = { name: 1 };  
  7. db.collection("employees").find().sort(mysort).toArray(function(err, result) {  
  8. if (err) throw err;  
  9. console.log(result);  
  10. db.close();  
  11. });  
  12. });  

Open the command terminal and run the following command:

  1. 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:

  1. var http = require('http');  
  2. var MongoClient = require('mongodb').MongoClient;  
  3. var url = "mongodb://localhost:27017/ MongoDatabase";  
  4. MongoClient.connect(url, function(err, db) {  
  5. if (err) throw err;  
  6. var mysort = { name: -1 };  
  7. db.collection("employees").find().sort(mysort).toArray(function(err, result) {  
  8. if (err) throw err;  
  9. console.log(result);  
  10. db.close();  
  11. });  
  12. });  

Open the command terminal and run the following command:

  1. Node sortdsc.js  

Node.js Sorting 2

Comment / Reply From