Mongodb-node.js Tutorial Series

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

Before proceeding any further let's display the contents 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 } ]
										
									


project() is the inbuilt method used along with find() to perform projection. We are using the details collection as data-set for our operation. we will be displaying the name and house field only. An example is given below :
													
//projection.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 code using the following command :
													
>node projection.js
Record Read successfully
[ { name: 'A', house: 'nilgiri', _id: 599bf49b7e063437b867ed4c },
  { name: 'C', house: 'nilgiri', _id: 599bf4ec10eb8b3a288b83b8 },
  { name: 'E', house: 'shivalik', _id: 599bf521beed503a009ee0b0 } ]

													
												

As we can 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 externally told by the code not to do so.
  • 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-id.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 code using the following command :
    													
    >node projection-id.js
    Record Read successfully
    [ { name: 'A' }, { name: 'C' }, { name: 'E' } ]
    
    													
    												

  • How to print all but given fields :
    													
    //projection-all.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 code using the following command :
    													
    >node projection-all.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 } ]
    
    													
    												

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. Projection in mongodb using node.js
  4. How to remove the _id field in mongodb using node.js
  5. How to print all but given fields in mongodb using node.js