Open In App

MongoDB Projection

Improve
Improve
Like Article
Like
Save
Share
Report

MongoDB provides a special feature that is known as Projection. It allows you to select only the necessary data rather than selecting whole data from the document. For example, a document contains 5 fields, i.e.,

{
name: "Roma",
age: 30,
branch: EEE,
department: "HR",
salary: 20000
}

But we only want to display the name and the age of the employee rather than displaying whole details. Now, here we use projection to display the name and age of the employee.

One can use projection with db.collection.find() method. In this method, the second parameter is the projection parameter, which is used to specify which fields are returned in the matching documents.

Syntax:

db.collection.find({}, {field1: value2, field2: value2, ..})
  • If the value of the field is set to 1 or true, then it means the field will include in the return document.
  • If the value of the field is set to 0 or false, then it means the field will not include in the return document.
  • You are allowed to use projection operators, but find() method does not support following projection operators, i.e., $, $elemMatch, $slice, and $meta.
  • There is no need to set _id field to 1 to return _id field, the find() method always return _id unless you set a _id field to 0.

Examples:

In the following examples, we are working with:

Database: GeeksforGeeks
Collection: employee
Document: five documents that contain the details of the employees in the form of field-value pairs.

Displaying the names of the employees –

Displaying the names of the employees without the _id field –

Displaying the name and the department of the employees without the _id field –

Displaying the names and the department of the employees whose joining year is 2018 –


Last Updated : 10 Feb, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads