文档菜单
文档首页
/ / /
Node.js 驱动程序
/ / /

指定要返回的字段

在本页中

  • 概述
  • 示例文档
  • 单个字段
  • 多个字段

使用投影来控制读取操作返回的文档中出现的字段。许多请求只需要某些字段,因此投影可以帮助您限制不必要的网络带宽使用。投影有两种方式

  • 显式包含具有值的字段1。这会隐式排除所有未指定的字段。

  • 隐式排除具有值的字段 0。这会隐式包含所有未指定的字段。

这两种投影方法互斥:如果您显式包含字段,则不能显式排除字段,反之亦然。

要遵循本指南中的示例,请使用以下代码片段将描述水果的文档插入到 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 },
]);

注意

您的查询操作可能返回一个包含匹配文档的游标引用。要了解如何检查游标中存储的数据,请参阅游标基础页面.

在以下查询中,将投影传递以仅返回每个文档的 name 字段

// return only* the name field
const projection = { name: 1 };
const cursor = myColl.find().project(projection);
for await (const doc of cursor) {
console.dir(doc);
}

投影文档为 name 指定了一个值为 1。这指示操作在结果中包含每个返回文档的 name 字段,并排除 qtyrating 字段。将此投影传递给具有空查询文档和没有排序文档的 find() 生成以下结果

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

尽管此投影仅显式包含了 name 字段,但查询还返回了 _id 字段。

_id 字段是一个特殊情况,因为它总是包含在每个查询中,除非明确指定不包含。这是因为 _id 是每个文档的唯一标识符,这是一个在构建查询时经常使用的属性。movies 集合数据展示了为什么这个属性是必要的:两部电影或多部电影可以共享相同的标题,例如电影的翻拍版本。因此,您需要一个唯一的 _id 值来可靠地引用特定的电影。_id 是投影中互斥的包含-排除行为中唯一的例外:即使明确包含其他字段,您也可以显式排除 _id,如果您不希望在返回的文档中包含 _id

// return only the name field
const projection = { _id: 0, name: 1 };
const cursor = myColl.find().project(projection);
for await (const doc of cursor) {
console.dir(doc);
}

投影文档为 name 指定了一个值为 1,并为 _id 指定了一个值为 0。这指示操作在结果中包含每个返回文档的 name 字段,并排除 _idqtyrating 字段。将此投影传递给具有空查询文档和没有排序文档的 find() 生成以下结果

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

您还可以指定要包含在投影中的多个字段。注意:在投影中指定字段的顺序不会改变它们返回的顺序。

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

以下示例中,标识了两个要包含在投影中的字段,得到以下结果

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

有关更多投影示例,请参阅《MongoDB 手册》中关于从查询返回投影字段的页面.

返回

限制返回结果