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, ..})
- 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, thefind()
method always return_id
unless you set a_id
field to 0.
Examples:
In the following examples, we are working with:
Database: w3wiki Collection: employee Document: five documents that contain the details of the employees in the form of field-value pairs.
Contact Us