MongoDB Project Fields

MongoDB Project Fields – In this MongoDB Tutorial, we shall learn to restrict only those fields to return in the result of a query.

In MongoDB Query Documents tutorial, we have learnt to filter MongoDB Documents based on a criteria, in which all the fields are returned in the result. But it is not always the case that we need all the fields in the result. We might be interested only on certain fields of the queried documents.

To limit the fields, we can make use of find() method. We can provide the required fields in a projection document and provide this projection document as second argument of find() method.

Syntax of find() method

Following is the syntax of find() method to accept projection document

where projection_document is

and projection_value can take 1 or 0.

Projection_valueDescription
1Include the field:value in Result
0Do not include the field:value in Result

 

Example – MongoDB Projection

Following is an example to limit fields in result using projection document.

  1. Select Database.
  2. Prepare projection document.
    When a projection document is provided, by default projection value of _id is 1. Change it to 0 if you do not require _id in the result. For rest of the fields you may set the projection value to 1, only for those required fields.
  3. Query with projection document provided as second argument to find() method.
    The result contains only those fields with respect to projection document.

 

Conclusion :

In this MongoDB Tutorial, we have learnt to limit the fields in the result using projection document as second argument to find() method.