Docs Home / Node.js Driver

Specify Which Fields to Return指定要返回的字段

Overview概述

Use a projection to control which fields appear in the documents returned by read operations. Many requests only require certain fields, so projections can help you limit unnecessary network bandwidth usage. Projections work in two ways:使用投影来控制哪些字段出现在读取操作返回的文档中。许多请求只需要某些字段,因此预测可以帮助您限制不必要的网络带宽使用。预测有两种方式:

  • Explicitly include fields with a value of 1. This has the side-effect of implicitly excluding all unspecified fields.显式地包含值为1的字段。这具有隐式排除所有未指定字段的副作用。
  • Implicitly exclude fields with a value of 0. This has the side-effect of implicitly including all unspecified fields.隐式排除值为0的字段。这具有隐式包含所有未指定字段的副作用。

These two methods of projection are mutually exclusive: if you explicitly include fields, you cannot explicitly exclude fields, and vice versa.这两种投影方法是互斥的:如果显式包含字段,则不能显式排除字段,反之亦然。

Sample Documents样本文档

To follow the examples in this guide, use the following code snippet to insert documents that describe fruits into the myDB.fruits collection:要遵循本指南中的示例,请使用以下代码片段将描述水果的文档插入到myDB.fruits集合中:

const myDB = client.db("myDB");
const myColl = myDB.collection("fruits");

await myColl.insertMany([
{ "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
{ "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
{ "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
{ "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
]);

Note

Your query operation may return a reference to a cursor that contains matching documents. To learn how to examine data stored in the cursor, see the Access Data From a Cursor page.您的查询操作可能会返回对包含匹配文档的游标的引用。要了解如何检查存储在游标中的数据,请参阅“从游标访问数据”页面。

Single Field单个字段

In the following query, pass the projection to only return the name field of each document:在以下查询中,传递投影以仅返回每个文档的name字段:

// return only* the name field仅返回*名称字段
const projectFields = { name: 1 };
const cursor = myColl.find().project(projectFields);
for await (const doc of cursor) {
console.dir(doc);
}

The projection document specifies a value of 1 for name. This instructs the operation to include the name field of each returned document in the results and exclude the qty and rating fields. 投影文档为name指定了一个值1。这指示操作在结果中包含每个返回文档的name字段,并排除qty(数量)和rating(评级)字段。Passing this projection to find() with an empty query document and no sort document yields the following results:将此投影传递给find(),并使用空查询文档和无排序文档,会产生以下结果:

{ "_id": 1, "name": "apples" }
{ "_id": 2, "name": "bananas" }
{ "_id": 3, "name": "oranges" }
{ "_id": 4, "name": "avocados" }

Although this projection only explicitly included the name field, the query returned the _id field as well.虽然这个投影只显式地包括name字段,但查询也返回了_id字段。

The _id field is a special case because it is always included in every query unless explicitly specified otherwise. _id字段是一个特例,因为除非另有明确规定,否则它总是包含在每个查询中。This is because _id is a unique identifier for each document, a property that is often used when constructing queries. 这是因为_id是每个文档的唯一标识符,这是构造查询时经常使用的属性。The movies collection data demonstrates why this property is necessary: two or more movies can share the same title, such as movie remakes. movies集合数据说明了为什么需要此属性:两部或多部电影可以共享同一标题,例如电影翻拍。Because of this, you need a unique _id value to reliably reference a specific movie. 因此,您需要一个唯一的_id值来可靠地引用特定的电影。_id is the only exception to the mutually exclusive include-exclude behavior in projections: you can explicitly exclude _id even when explicitly including other fields if you do not want _id to be present in returned documents._id是投影中互斥的include-exclude行为的唯一例外:如果不希望_id出现在返回的文档中,即使显式包含其他字段,也可以显式排除_id

// return only the name field仅返回名称字段
const projectFields = { _id: 0, name: 1 };
const cursor = myColl.find().project(projectFields);
for await (const doc of cursor) {
console.dir(doc);
}

The projection document specifies a value of 1 for name and 0 for _id. 投影文档为name指定值1,为_id指定值0This instructs the operation to include the name field of each returned document in the results and exclude the _id, qty, and rating fields. 这指示操作在结果中包含每个返回文档的name字段,并排除_idqtyrating字段。Passing this projection to find() with an empty query document and no sort document yields the following results:将此投影传递给find(),并使用空查询文档和无排序文档,会产生以下结果:

{ "name": "apples" }
{ "name": "bananas" }
{ "name": "oranges" }
{ "name": "avocados" }

Multiple Fields多个字段

You can also specify multiple fields to include in your projection. Note: the order in which you specify the fields in the projection does not alter the order in which they are returned.您还可以指定多个字段以包含在投影中。注意:在投影中指定字段的顺序不会改变它们返回的顺序。

const projectFields = { _id: 0, rating: 1, name: 1 };
const cursor = myColl.find().project(projectFields);
for await (const doc of cursor) {
console.dir(doc);
}

This example that identifies two fields to include in the projection yields the following results:此示例标识了要包含在投影中的两个字段,得出以下结果:

  { "name": "apples", "rating": 3 }
{ "name": "bananas", "rating": 1 }
{ "name": "oranges", "rating": 2 }
{ "name": "avocados", "rating": 5 }

For more projection examples, see the MongoDB Manual page on Project Fields to Return from Query.有关更多投影示例,请参阅MongoDB手册中关于从查询返回的项目字段的页面。

Note

You must chain a cursor method such as sort(), limit(), skip(), or project() to a read operation before iterating the cursor. 在迭代游标之前,必须将游标方法(如sort()limit()skip()project())链接到读取操作。If you specify a cursor method after iterating the cursor, the setting does not apply to the read operation.如果在迭代游标后指定游标方法,则该设置不适用于读取操作。