For AI agents: a documentation index is available at https://www.mongodb.com/ja-jp/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

Projection and Query Performance

By default, MongoDB returns every field in each document that matches a query, even when your application only reads a few of them. A projection restricts a query to the fields you need, which reduces the amount of data MongoDB has to serialize and send to your application.

Additionally, a projection can improve query performance through covered queries. If an index contains all the fields in a projection, MongoDB can skip reading the documents and return data directly from the index.

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

Some collections store large documents, such as those containing full text fields, embedded arrays, or binary data. When you query these collections, returning entire documents can transfer far more data than your application needs.

Your application may read only a few fields from each result, such as a title and a date. In that case, use a projection to return just those fields. MongoDB then serializes and sends less data, and your application processes less data in turn.

Reading full documents also costs more on the server. Pulling large documents from disk into the cache can evict data that other queries need. You can avoid this with an index. If an index covers all fields in the projection, MongoDB skips loading the document into the cache and instead serves the data from the index.

Some queries run far more often than others, such as a query behind a dashboard widget, a list view, or a polling endpoint. Even a small amount of unused data in each result adds up when a query runs thousands or millions of times.

If a query runs frequently, project to only the fields your application needs. Doing so reduces the cumulative network and processing cost across every call, even when the per-call savings look small in isolation.

Some queries read only a few fields that an index already stores. One example is a lookup that filters on one field and returns one other. Reading documents from the collection adds work that the index alone could absorb.

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.

When the projection contains some fields covered by an index and some that are not, MongoDB uses the index to find the documents, then must read them to build the results.

But if a single index contains both the filter fields and the projected fields, MongoDB answers the query directly from the index, without reading the documents. This can significantly improve query execution.

For details, see Run Covered Queries.

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.

Using a $project stage at the beginning or middle of a pipeline to reduce the number of fields passed to subsequent pipeline stages is unlikely to improve performance, because the database performs this optimization automatically.

Note

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

For more information on aggregation pipeline optimization, see Aggregation Pipeline Optimization.

This example uses the database profiler to measure how much data MongoDB returns to your application. It shows how a projection reduces that amount and how a covering index reduces it further.

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.', ... }, '...']

Each result is a complete document, including several long free-text fields. The full output is too large to display here.

3

Run the same query with a projection that restricts the results to the fields you need:

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.

Both queries examine the same number of documents. The savings come from the amount of data MongoDB needs to serialize and send back to the client.

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

Without a supported index, MongoDB examines every document in the collection to apply the filter, even though the projection limits which fields the query returns. No index keys are read.

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

Create an index on the filter field:

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.

Run the query again and check the counters again:

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

Check the stages in the new explain output:

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

Create a compound index on the filter field and the projected fields:

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

With the covering index, MongoDB doesn't examine any documents. It scans index keys instead.

11

Check the stages in the new explain output:

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

The explain output also reports how long MongoDB takes to execute this query. Compare the execution time of the covered query with that of the collection scan:

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

The covered query executes in a fraction of the time of the collection scan. For more information, see Run Covered Queries.

13

Restore the default profiling level so that MongoDB stops logging every operation:

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