In this Chapter , we will learn about Sorting the collection in either ascending or descending order using sort mechanism of mongodb using nodejs
Step - 1 : Including Packages
We will start by
requiring the package.
We are using the following package in our application :
var mongo = require('mongodb');
Step - 2 : Establish Connection
Now let's establish a connection between the mongoDb Database and our node.js application.
var new_db = "mongodb://localhost:27017/demo_db"
Step - 3 : Sort
Sort() is the not a method hence it can not be used standalone so we, in most
of the cases, use it along with find() method of mongodb.It is used to sort the collection
in either ascending of descending order.
Syntax
The syntax for sort() is :
db.collection(NAME_OF_THE_COLLECTION).find().sort(SORTING_METHOD).toArray( (CALLBACK_FUNCTION) => {});
//sort-mongodb-nodejs.js
var mongo = require('mongodb');
var new_db = "mongodb://localhost:27017/demo_db"
//connecting to db
mongo.connect(new_db ,(error , db) => {
if (error){
throw error;
}
//condition "1" for sorting in Ascending order on the basis of "age"
var method = { age : 1 };
//accessing the collection
db.collection("new").find().sort(method).toArray( (err , collection) => {
if(err) throw err;
//console.log(collection.result.n + "Record(s) deleted successfully");
console.log(collection);
db.close();
});
});
D:\nj-learn-mongo>node sort-mongodb-nodejs.js
D:\nj-learn-mongo>node sort-mongodb-nodejs.js
[ { name: 'E', age: '15', _id: 5981afe5c4ac876c0833112b },
{ name: 'C', age: '21', _id: 5981afbaef52977a9c08e68b },
{ name: 'A', age: '22', _id: 5981af956609e37650f56c62 },
{ name: 'D', age: '29', _id: 5981b01889a0597ad05a7657 },
{ name: 'G', age: '34', _id: 5981afd5f3ba3d7a7cbe5465 },
{ name: 'B', age: '67', _id: 5981afa7d8942377fced6c00 } ]
//sort-mongodb-nodejs.js
var mongo = require('mongodb');
var new_db = "mongodb://localhost:27017/demo_db"
//connecting to db
mongo.connect(new_db ,(error , db) => {
if (error){
throw error;
}
//condition "-1" for sorting in descending order on the basis of "name"
var method = { name : -1 };
//accessing the collection
db.collection("new").find().sort(method).toArray( (err , collection) => {
if(err) throw err;
//console.log(collection.result.n + "Record(s) deleted successfully");
console.log(collection);
db.close();
});
});
D:\nj-learn-mongo>node sort-mongodb-nodejs.js
D:\nj-learn-mongo>node sort-mongodb-nodejs.js
[ { name: 'G', age: '34', _id: 5981afd5f3ba3d7a7cbe5465 },
{ name: 'E', age: '15', _id: 5981afe5c4ac876c0833112b },
{ name: 'D', age: '29', _id: 5981b01889a0597ad05a7657 },
{ name: 'C', age: '21', _id: 5981afbaef52977a9c08e68b },
{ name: 'B', age: '67', _id: 5981afa7d8942377fced6c00 },
{ name: 'A', age: '22', _id: 5981af956609e37650f56c62 } ]