Node js MongoDB Sorting - Node JS tutorial




How to Sorting of MongoDB in Node.js?

  • In MongoDB, the sort() method is to sort the result in ascending or descending order.
  • learn nodejs - node-js tutorial - node js mongodb sorting - nodejs examples -  nodejs programs

    Learn Node js - node js Tutorial - Node JS Mongodb Sorting - node - Node js Examples

  • The sort() method use one parameter, to define object sorting order.
 node-js  sorting

Learn Node js - node js Tutorial - node-js sorting - node - Node js Examples

Value used for sorting in ascending order:

{ name: 1 }  

Read Also

Oracle Sort

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":

sortasc.js

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();  
});  
});  

Output

Open the command terminal and run the following command: Node sortasc.js

 ascending order in node.js mongodb sorting

Learn Node js - node js Tutorial - ascending order in node.js mongodb sorting - node - Node js Examples

Read Also

PHP Sort Function.

Sort in Descending Order

Example

  • Sort the records in descending order according to name
  • Create a js file named "sortdsc.js":

sortdsc.js

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();  
});  
});  

Output

Open the command terminal and run the following command: Node sortdsc.js

 descending order in node.js mongodb sorting

Learn Node js - node js Tutorial - descending order in node.js mongodb sorting - node - Node js Examples



Related Searches to Node JS MongoDB Sorting - Node JS tutorial