AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.

프로젝션 및 쿼리 성능

기본적으로 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

새로운 explain 출력에서 단계를 확인하세요:

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

새로운 explain 출력에서 단계를 확인하세요:

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

explain 출력에는 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 }
이 페이지 평가하기