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:


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


The 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

No comments:

Post a Comment

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

Related Posts

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...