MongoDB: Projection

What is MongoDB Projection?

Projection in MongoDB is a special type of feature that is used to select only a part of the data, despite selecting the entire data present inside the document. Projection is mainly performed using the find() method in MongoDB.

Let's suppose you have the following 2 documents present inside a database:

MongoDB: Projection

Now, for every employee, it is very confidential to disclose the salary. Therefore, we only want to fetch the Name of the employee from every document present inside the Database. This is where the projection will play a vital role. The below image clearly displays the functioning of Projection:

MongoDB: Projection

Syntax

find( filter, {field1: value1 in 0 or 1, field2: value2 in 0 or 1...})

NOTE: 

  1. If field: 0, that means this field will not be displayed as an output.
  2. If field: 1, that means this field will be displayed as an output.
  3. _id field is by default set as 1. If you don't want to include the _id field in the output, you need to set its value as 0.

Example

You have a collection with certain documents as shown below:

MongoDB: Projection

Moving ahead, you want to limit the selection by displaying only Names. You can do it using projection as follows:

 db.edatabase.find({},{Name:1,_id:0})

Output

MongoDB: Projection