Node js - MongoDB Sorting - Node JS tutorial
MongoDB Sort in Node.js

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 SortValue 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

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

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