Mongodb-node.js Tutorial Series

Sort mongodb collection using node.js

MongoDB-Nodejs tutorial | Perform mongodb operations using node.js



Overview

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.

Let's Start !!
Step 1 - Include Package

We will start by including mongodb npm package as shown below :

												
var mongo = require('mongodb');
												
											

Step-2 : Establish Connection

Establish a connection between the mongoDb database and our node.js app using the following :

												
var new_db = "mongodb://localhost:27017/demo_db"
												
											

  • demo_db is the name of the database. You can change it in accordance with your database name.
  • 27017 is the port where mongoDb is running.
  • Localhost i.e. 127.0.0.1 is the local IP.

Step-3 : Sort collection

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) => {});
										
									

You can give 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.
  1. ASCENDING :
    													
    //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();
    	});
    });
    													
    												

    You can run the above code using the following command :
    													
    >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 } ]
    
    													
    												

  2. DESCENDING :
    													
    //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();
    	});
    });
    													
    												

    You can run the above code using the following command :
    													
    >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 } ]
    
    													
    												

What we learned

In this article we learned about

  1. Including monogdb npm package in your app.
  2. Establishing a connection between mongodb database and node.js application.
  3. sort method in mongodb to sort collection in ascending order using node.js
  4. sort method in mongodb to sort collection in descending order using node.js