MongoDB - Projection

MongoDB - Projection

find() method

The find() method described in the MongoDB Query Document takes an optional second parameter, which is the list of fields you want to retrieve. In MongoDB, when you execute the find() method , it displays all the fields in the document. To limit this, you need to set the list of fields to 1 or 0. 1 is used to show the field and 0 is used to hide the fields.

Syntax

The basic syntax of the find() method with projection is as follows:

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

example

Consider a collection mycol having the following data −

{ "_id" : ObjectId ( 5983548781331adf45ec5 ), "title" : "MongoDB Overview" } { "_id" : ObjectId ( 5983548781331adf45ec6 ), "title" : "NoSQL Overview" } { "_id" : ObjectId ( 5983548781331adf45ec7 ), "title " : "Tutorials Point Overview" }    
    
    

The following example will display the title of the document when the document is requested.

> db . mycol . find ({},{ "title" : 1 , _id : 0 }) { "title" : "MongoDB Overview" } { "title" : "NoSQL Overview" } { "title" : "Tutorials Point Overview" } >



Note that the _id field is always shown when executing the find() method , if you don't want this field you need to set it to 0.