对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

投影和查询性能

默认情况下,MongoDB 会返回每个文档中与查询匹配的所有字段,即使您的应用程序只读取其中的几个字段。投影可以将查询限制为所需的字段,从而减少 MongoDB 需要序列化并发送给应用程序的数据量。

此外,投影可以通过覆盖查询来提升查询性能。如果索引包含了投影中的所有字段,MongoDB 就可以跳过读取文档的步骤,直接从索引返回数据。

You can apply a projection through the field argument of a query or through a $project stage in an aggregation pipeline.

有些集合存储大型文档,例如包含全文字段、嵌入式数组或二进制数据的文档。查询这些集合时,返回整个文档可能会传输远超应用程序实际需求的数据量。

您的应用程序可能只会从每个结果中读取几个字段,例如标题和日期。在这种情况下,请使用投影来仅返回这些字段。这样,MongoDB 序列化和发送的数据量就会减少,您的应用程序也需要处理的数据量相应减少。

读取完整文档也会增加服务器的开销。将大型文档从磁盘加载到缓存中可能会占用其他查询所需的数据。使用索引可以避免这种情况。如果索引涵盖了投影中的所有字段,MongoDB 就不会将文档加载到缓存中,而是直接从索引中提供数据。

有些查询的运行频率远高于其他查询,例如仪表板小部件、列表视图或轮询端点背后的查询。即使每次结果中只有少量未使用的数据,当查询运行成千上万次时,累积起来也会造成很大的浪费。

如果查询频繁运行,请仅投影应用程序所需的字段。这样做可以降低每次调用的累计网络和处理成本,即使单独来看,每次调用节省的成本似乎很小。

有些查询仅读取索引中已存储的几个字段。例如,一个查找查询会根据一个字段进行筛选,并返回另一个字段。从集合中读取文档会增加额外的工作量,而这些工作仅靠索引就能完成。

If an index already stores the fields you filter on and the fields you return, project to only those fields and exclude _id. MongoDB then serves the query as a covered query, reading no documents at all.

当投影包含一些索引涵盖的字段和一些索引未涵盖的字段时,MongoDB 使用索引查找文档,然后必须读取它们来构建结果。

但如果单个索引同时包含筛选字段和投影字段,MongoDB 可以直接从索引中响应查询,而无需读取文档。这可以显著提高查询执行速度。

有关详细信息,请参阅“运行覆盖查询”。

In an aggregation pipeline, a $project stage serves the same purpose as a query projection: it restricts the fields in the documents the pipeline outputs.

When you use a $project stage stage it should typically be the last stage in your pipeline, used to specify which fields to return to the client.

在管道的开头或中间使用 $project 阶段来减少传递到后续管道阶段的字段数量不太可能提高性能,因为数据库会自动执行此优化。

注意

The query optimizer can add an internal projection. Pipelines containing only $count or $group stages are covered queries when they reference only indexed fields.

有关聚合管道优化的更多信息,请参阅聚合管道优化。

本示例使用数据库分析器来测量 MongoDB 向应用程序返回的数据量。它展示了投影如何减少数据量,以及覆盖索引如何进一步减少数据量。

The example also uses the listingsAndReviews collection from the sample_airbnb sample database. For more information on loading the sample database, see Load Sample Data Into A Local Deployment.

1

For this example, set the profiling level to 2. This setting causes MongoDB to log every operation to the system.profile collection.

db.setProfilingLevel(2)
{ was: 0, slowms: 100, sampleRate: 1, ok: 1 }
2

Run a query that returns every field in the first 100 matching documents:

db.listingsAndReviews.find( { bedrooms: { $gt: 1 } }).limit(100).toArray()
[ { _id: '10006546', listing_url: 'https://www.airbnb.com/rooms/10006546', name: 'Ribeira Charming Duplex', summary: 'Fantastic duplex apartment with three bedrooms, located in the historic area of Porto, Ribeira (Cube) - UNESCO World Heritage Site. Centenary building fully rehabilitated, without losing their original character.', ... }, '...']

每个结果都是一份完整的文档,包含多个较长的自由文本字段。完整输出内容过多,无法在此处显示。

3

运行相同的查询,但使用投影将结果限制为所需的字段:

db.listingsAndReviews.find( { bedrooms: { $gt: 1 } }, { name: 1, bedrooms: 1 }).limit(100).toArray()
[ { _id: '10006546', name: 'Ribeira Charming Duplex', bedrooms: 3 }, { _id: '10047964', name: 'Charming Flat in Downtown Moda', bedrooms: 2 }, { _id: '10066928', name: '3 chambres au coeur du Plateau', bedrooms: 3 }, '...']
4

Check the most recent entries in the system.profile collection and compare the responseLength values:

const unprojectedLength = db.system.profile.find( { "command.find": "listingsAndReviews", "command.projection": { $exists: false } }).sort({ ts: -1 }).limit(1).next().responseLength; const projectedLength = db.system.profile.find( { "command.find": "listingsAndReviews", "command.projection": { $exists: true } }).sort({ ts: -1 }).limit(1).next().responseLength; console.log(`Response is ${projectedLength} bytes projected, ${unprojectedLength} bytes unprojected\nProjection smaller: ${projectedLength < unprojectedLength}`)
Response is 8765 bytes projected, 2163956 bytes unprojectedProjection smaller: true

The documents in listingsAndReviews are large. In this example, the projection reduces the response size from 2 MB to under 9 KB.

这两个查询检查的文档数量相同。节省的空间来自于 MongoDB 需要序列化并发送回客户端的数据量。

5

To diagnose the query further, run it again with the cursor.explain("executionStats") method and store the result's executionStats object in an es variable. The steps that follow reuse es, so run them in the same mongosh session:

let es = db.listingsAndReviews.find( { bedrooms: { $gt: 1 } }, { name: 1, bedrooms: 1 }).explain("executionStats").executionStats;console.log(`Examined ${es.totalKeysExamined} keys, ${es.totalDocsExamined} documents\nKeys Used: ${es.totalKeysExamined > 0}\nCovered: ${es.totalDocsExamined === 0}`)
Examined 0 keys, 5555 documentsKeys Used: falseCovered: false

The block reports how many keys and documents the query examines, as recorded in the executionStats.totalKeysExamined and executionStats.totalDocsExamined fields.

6

如果没有受支持的索引,即使投影限制了查询返回的字段,MongoDB 也会检查集合中的每个文档来应用过滤器。不会读取任何索引键。

The explain output also shows which stages MongoDB uses to run the query. An IXSCAN stage means MongoDB scans an index, and a FETCH stage means it reads documents from the collection. Check the stages in the stored explain output:

JSON.stringify(es.executionStages).match(/COLLSCAN|IXSCAN|FETCH/g)
[ 'COLLSCAN' ]

With no index available, the plan is a collection scan (COLLSCAN), which reads every document directly. The plan contains neither IXSCAN nor FETCH.

7

Save the query's execution time from the executionStats.executionTimeMillis field to compare with the covered query later:

let unindexedMillis = es.executionTimeMillis
8

在筛选字段上创建索引:

db.listingsAndReviews.createIndex({ bedrooms: 1 })

The index contains bedrooms, but not name. The projection still requires that field, so MongoDB cannot answer the query from the index alone.

再次运行查询并再次检查计数器:

es = db.listingsAndReviews.find( { bedrooms: { $gt: 1 } }, { name: 1, bedrooms: 1 }).explain("executionStats").executionStats;console.log(`Examined ${es.totalKeysExamined} keys, ${es.totalDocsExamined} documents\nKeys Used: ${es.totalKeysExamined > 0}\nCovered: ${es.totalDocsExamined === 0}`)
Examined 1746 keys, 1746 documentsKeys Used: trueCovered: false

The index helps MongoDB find the matching documents by scanning index keys, but the projection needs name, which the index doesn't store. MongoDB must still read every matching document to build the results.

9

请查看新的解释输出中的各个阶段:

JSON.stringify(es.executionStages).match(/COLLSCAN|IXSCAN|FETCH/g)
[ 'FETCH', 'IXSCAN' ]

The plan now contains FETCH and IXSCAN stages, which indicate that MongoDB scans the index to find matching documents, then fetches each full document to retrieve the additional field needed for the projection.

10

在筛选字段和投影字段上创建复合索引:

db.listingsAndReviews.createIndex({ bedrooms: 1, name: 1 })

This index contains every field the projection returns. A query is covered only when the index contains all returned fields, and by default MongoDB includes the _id field in every document it returns.

Adjust your projection to exclude _id, then run the query again and check the counters one last time:

es = db.listingsAndReviews.find( { bedrooms: { $gt: 1 } }, { name: 1, bedrooms: 1, _id: 0 }).explain("executionStats").executionStats;console.log(`Examined ${es.totalKeysExamined} keys, ${es.totalDocsExamined} documents\nKeys Used: ${es.totalKeysExamined > 0}\nCovered: ${es.totalDocsExamined === 0}`)
Examined 1746 keys, 0 documentsKeys Used: trueCovered: true

使用覆盖索引时,MongoDB 不会检查任何文档,而是扫描索引键。

11

请查看新的解释输出中的各个阶段:

JSON.stringify(es.executionStages).match(/COLLSCAN|IXSCAN|FETCH/g)
[ 'IXSCAN' ]

The plan contains an IXSCAN stage and no FETCH stage, which indicates that MongoDB answers the query with an index scan only and doesn't need to read the full document to handle the projection.

12

解释输出还会报告 MongoDB 执行此查询所需的时间。请将所涵盖查询的执行时间与集合扫描的执行时间进行比较:

console.log(`Execution Times:\n- Unindexed Query: ${unindexedMillis} ms\n- Covered Query: ${es.executionTimeMillis} ms`)
Execution Times:- Unindexed Query: 5 ms- Covered Query: 1 ms

覆盖查询的执行时间仅为集合扫描的几分之一。有关更多信息,请参阅“运行覆盖查询”。

13

恢复默认的性能分析级别,使 MongoDB 停止记录每个操作:

db.setProfilingLevel(0)
{ was: 2, slowms: 100, sampleRate: 1, ok: 1 }
给本页内容打分