MongoDB Projection - MongoDB

What is MongoDB Projection?

In MongoDB, projection means selecting only the required data rather than selecting whole document data. If a document has 5 fields and if you want to show only 3, then you have to select only 3 fields from them.

find() Method

MongoDB's find() method, explained in MongoDB Query Document will accept second optional parameter which is a list of fields you wish to retrieve. In MongoDB, when find() method is executed, it will display all the fields of a document. To restrict this, you have to set a list of fields with value 1 or 0. 1 is used for showing the field and 0 is used for hiding the fields.

Syntax

Basic syntax of find() method with projection is as follows

Example

Consider collection mycol has below data

Below example will display the title of the document while querying the document.

Please note _id field is always displayed while executing find() method, if you don't need this field, then you have to set it as 0.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

MongoDB Topics