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. No,w 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 –

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.