Mongodb 简明教程

MongoDB - Projection

在 MongoDB 中,投影是指仅选择必要的数据,而不选择文档的全部数据。如果某个文档有 5 个字段,并且你只需要显示 3 个,那么只从中选择 3 个字段即可。

In MongoDB, projection means selecting only the necessary data rather than selecting whole of the data of a document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them.

The find() Method

MongoDB 的 find() 方法(在 MongoDB Query Document 中进行了说明)接受第二个可选参数,即希望检索的字段列表。在 MongoDB 中,执行 find() 方法时,它会显示文档的所有字段。要限制此行为,需要设置一个带有值 1 或 0 的字段列表。1 用于显示字段,0 用于隐藏字段。

MongoDB’s find() method, explained in MongoDB Query Document accepts second optional parameter that is list of fields that you want to retrieve. In MongoDB, when you execute find() method, then it displays all fields of a document. To limit this, you 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 fields.

Syntax

find() 方法与投影结合起来的基本语法如下:

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

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

Example

考虑集合 mycol 具有以下数据:

Consider the collection mycol has the following data −

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

下面的示例将在查询文档时显示文档的标题。

Following example will display the title of the document while querying the document.

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

请注意,在执行 find() 方法时始终会显示 _id 字段,如果你不想要此字段,那么需要将其设置为 0。

Please note _id field is always displayed while executing find() method, if you don’t want this field, then you need to set it as 0.