Projection in MongoDB

In MongoDB, we will use projection when we need to select only the 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 the second optional parameter that is a 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 the find() method, then it will show all fields of a document. To restrict this, we need to set a 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:


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"}

The below-given example will display the title of the document while querying the document.

{"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

No comments:

Post a Comment

Please do not enter any spam link in the comment box.

Related Posts

Fatal Error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails.

Problem: Sometimes, we get the following error when trying to make a connection in Rails.  FATAL ERROR: Peer authentication failed for us...