Performing projection on mongodb collection using nodejs


What do we intend to make ?

By default , if we perform any query on a mongodb collection it tends to return all the data of a field in the matching document. So in order to avoid that we use projection. Projections limit the fields returned by the query.The projection document can specify the inclusion as well as exclusion of the fields as shows below:
{ field-name-1 : value , field-name-2 : value .... so on}
here value can be either 1 or 0 where 1 signifies inclusion and 0 signifies exclusion

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 : Projection

  • Before proceeding any further let's display the content of the collection first. We have already covered how we can read the collection.
    		        
    node read-all-occurance-mongodb-nodejs.js
    Record Read successfully
    [ { name: 'A',
        section: 'arts',
        roll: '2',
        house: 'nilgiri',
        _id: 599bf49b7e063437b867ed4c },
      { name: 'B',
        section: 'commerce',
        roll: '12',
        house: 'shivalik',
        _id: 599bf4c65ef24a38a44bdf17 },
      { name: 'C',
        section: 'arts',
        roll: '1',
        house: 'nilgiri',
        _id: 599bf4ec10eb8b3a288b83b8 },
      { name: 'E',
        section: 'arts',
        roll: '10',
        house: 'shivalik',
        _id: 599bf521beed503a009ee0b0 },
      { name: 'D',
        section: 'commerce',
        roll: '5',
        house: 'nilgiri',
        _id: 599bf5547157e933f803bfaf } ]
    				
    	            

  • performing the projection
    project() is used along with find() to perform projection. We are using the details collection as dataset for our operation. we will be displaying the name , house field only.
    		        
    //projection-mongodb-nodejs.js
    var mongo = require('mongodb');
    var new_db = "mongodb://localhost:27017/demo_db"
    
    mongo.connect(new_db , function(error , db){
    	if (error){
    		throw error;
    	}	
    	db.collection("details").find({ section : "arts"}).project({name:1 , house : 1}).toArray( (err , collection) => {
    		if(err) throw err;
    		console.log("Record Read successfully");
    		console.log(collection);
    		db.close();
    	});
    });
    				
    	            

    You can run the above program as follows :
    		        
    
    >node projection-mongodb-nodejs.js
    
    				
    	            

    And the output of the above code is :
    		        
    
    >node projection-mongodb-nodejs.js
    Record Read successfully
    [ { name: 'A', house: 'nilgiri', _id: 599bf49b7e063437b867ed4c },
      { name: 'C', house: 'nilgiri', _id: 599bf4ec10eb8b3a288b83b8 },
      { name: 'E', house: 'shivalik', _id: 599bf521beed503a009ee0b0 } ]
    
    
    				
    	            

    if you'll observe along with name and house field , _id field is also displayed. The reason being the default value set for _id field is 1. So , it will be printed by default unless told by the code not to do so as shown below.
  • How to remove the _id field ?
    In order to remove the _id field we just need to set it to 0. This code will print just the name of the students pursuing arts section.
    		        
    //projection-mongodb-nodejs.js
    var mongo = require('mongodb');
    var new_db = "mongodb://localhost:27017/demo_db"
    
    mongo.connect(new_db , function(error , db){
    	if (error){
    		throw error;
    	}	
    	db.collection("details").find({ section : "arts"}).project({_id:0 , name : 1}).toArray( (err , collection) => {
    		if(err) throw err;
    		console.log("Record Read successfully");
    		console.log(collection);
    		db.close();
    	});
    });
    
    				
    	            

    You can run the above program as follows :
    		        
    
    >node projection-mongodb-nodejs.js
    
    				
    	            

    And the output of the above code is :
    		        
    
    >node projection-mongodb-nodejs.js
    Record Read successfully
    [ { name: 'A' }, { name: 'C' }, { name: 'E' } ]
    
    				
    	            

  • How to print all but excluded fields ?

    		        
    //projection-mongodb-nodejs.js
    var mongo = require('mongodb');
    var new_db = "mongodb://localhost:27017/demo_db"
    
    mongo.connect(new_db , function(error , db){
    	if (error){
    		throw error;
    	}	
    	db.collection("details").find({}).project({section : 0 , roll : 0}).toArray( (err , collection) => {
    		if(err) throw err;
    		console.log("Record Read successfully");
    		console.log(collection);
    		db.close();
    	});
    });
    				
    	            

    You can run the above program as follows :
    		        
    
    >node projection-mongodb-nodejs.js
    
    				
    	            

    And the output of the above code is :
    		        
    
    >node projection-mongodb-nodejs.js
    Record Read successfully
    [ { name: 'A', house: 'nilgiri', _id: 599bf49b7e063437b867ed4c },
      { name: 'B', house: 'shivalik', _id: 599bf4c65ef24a38a44bdf17 },
      { name: 'C', house: 'nilgiri', _id: 599bf4ec10eb8b3a288b83b8 },
      { name: 'E', house: 'shivalik', _id: 599bf521beed503a009ee0b0 },
      { name: 'D', house: 'nilgiri', _id: 599bf5547157e933f803bfaf } ]