Projection in MongoDB

In MongoDB, projection's meaning is to select only the necessary data instead of selecting the entire data of a Document. If a Document has 5 fields and you only need 3 fields, you should only select 3 fields from that Document.

In MongoDB, projection's meaning is to select only the necessary data instead of selecting the entire data of a Document. If a Document has 5 fields and you only need 3 fields, you should only select 3 fields from that Document.

The find () method in MongoDB

The find () method in MongoDB, explained in Query Document, accepts the second arbitrary parameter which is a list of the fields you want to retrieve. In MongoDB, when you execute the find () method, it displays all the fields of a Document. To limit this, you need to set a list of fields with a value of 1 or 0. Value 1 is used to display the field, while 0 is used to hide the field.

Syntax

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

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

For example

You follow Collection with the name mycol with 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 displays the title of the Document while querying it.

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

You should note that the _id field is always displayed while executing the find () method, if you don't want this field, then you set it to 0.

According to Tutorialspoint

Previous article: Delete Document in MongoDB

Next article: Limit the record in MongoDB

4.5 ★ | 2 Vote