Jul 5, 2015

Projection in MongoDB

In MongoDB we will use projection when we need to select only necessary data from our data document. If a document has 8 fields and we need to show only 3, then we will select only 3 fields form data document.

Previously we explained MongoDB's find() method in MongoDB Query Document accepts second optional parameter that is list of fields when we want to retrieve data from the  fields then we will use the list of fields. In MongoDB's  Collection when we execute find() method, then it will show all fields of a document. To restrict this we need to set list of fields with value 1 or 0. 1 is used to show the field while 0 is used to hide the field.
SYNTAX: Basic syntax of find() method with projection is given below:


>db.COLLECTION_NAME.find({},{KEY:1})


EXAMPLE: Consider the collection mycol has given below data:


{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview","by":"codefari"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"MongoDB Query overview","by":"codefari"}


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


>db.mycol.find({},{"title":1,_id:0,"by":0})
{"title":"MongoDB Overview"}
{"title":"MongoDB Query overview"}
> 


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