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

db.collection.find(query_document, projection_document)

where projection_document is

{field1:projection_value, field1:projection_value, ..}

and projection_value can take 1 or 0.

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

Example – MongoDB Projection

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

Select Database.

> use tutorialkart
switched to db tutorialkart

Prepare projection document.

> projection_doc={"name":1,"place":1,_id:0}
{ "name" : 1, "place" : 1, "_id" : 0 }

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.

Query with projection document provided as second argument to find() method.

> db.people.find({},projection_doc)
{ "name" : "Midhuna", "place" : "Amaravati" }
{ "name" : "Akhil", "place" : "New York" }
{ "name" : "Honey" }
{ "name" : "Manju", "place" : "Vizag" }
{ "name" : "Bharat", "place" : "New York" }
{ "name" : "Arya" }

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.