Node js - MongoDB Sorting - Node JS tutorial




MongoDB Sort 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

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add wikitechy.com to your ad blocking whitelist or disable your adblocking software.

×