In this part of the mongodb operations using node.js tutorial series , we will learn about how we can
sort
a mongodb collection in either ascending or descending order using node.js
.
We will start by including mongodb
npm package as shown below :
var mongo = require('mongodb');
Establish a connection between the mongoDb database and our node.js app using the following :
var new_db = "mongodb://localhost:27017/demo_db"
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.
It's syntax is :
db.collection(NAME_OF_THE_COLLECTION).find().sort(SORTING_METHOD).toArray( (CALLBACK_FUNCTION) => {});
1
if we want to sort in ascending
order along with the paramter.
and -1
if you want to sort in descending order. Examples of both are given below.
//ascending.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();
});
});
>node ascending.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 } ]
//descending.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();
});
});
>node descending.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 } ]
In this article we learned about
monogdb
npm package in your app. sort
method in mongodb to sort collection in ascending
order using node.jssort
method in mongodb to sort collection in descending
order using node.js