Open In App

MongoDB Projection

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, ..})

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 –

Article Tags :