Sort the collection in Mongodb database using Node.js


What do we intend to make ?

In this Chapter , we will learn about Sorting the collection in either ascending or descending order using sort mechanism of mongodb using nodejs

Let's Start !

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"



                
	            

  • demo_db is the name of the database. You can change it as per your wish.
  • 27017 is the port where our mongoDb is running.
  • Localhost i.e. 127.0.0.1 is the local IP.

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

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 :

    		        
    //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();
    	});
    });
    
    
    
    
    
                    
    	            

    You can run the above code using the following command :

    		        
    
    D:\nj-learn-mongo>node sort-mongodb-nodejs.js
    
    				
    	            

    The output of the above code is :

    		        
    
    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 } ]
    
    
    
    
    				
    	            


  2. DESCENDING :

    		        
    //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();
    	});
    });
    
    
    
    
    
                    
    	            

    You can run the above code using the following command :

    		        
    
    D:\nj-learn-mongo>node sort-mongodb-nodejs.js
    
    				
    	            

    The output of the above code is :

    		        
    
    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 } ]