English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MongoDB Document Projection

In MongoDB, projection means to select only the necessary data instead of selecting all the data of the entire document. If a document has5fields, while you only need to display3fields, then you just need to select3field.

find() method

MongoDB's find() method, in MongoDBQuery documentIt explains that it accepts the second optional parameter, which is the list of fields you want to retrieve. In MongoDB, when you execute the find() method, it will display all fields of the document. To limit this, you need to set the value to1field list or 0.1Used to display fields, while 0 is used to hide fields.

Syntax

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

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

Example

Assuming the collection mycol has the following data-

{_id : ObjectId("507f191e810c19729de860e1", title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2", title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3", title: "w3codebox Overview"}

The following example will display the document title when querying the document.

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

Note_idAlways displays when executing the find() method, if you do not want this field, you need to set it to 0.