0Pricing
MongoDB Academy · 강의

인덱스 교차와 복합 인덱스 비교

학습자는 MongoDB가 여러 단일 필드 인덱스를 교차 사용하는 경우와 복합 인덱스가 교차보다 우수한 경우를 이해합니다.

인덱스 교차와 복합 인덱스 비교은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What Is Index Intersection?

Index intersection is MongoDB's ability to use two or more single-field indexes simultaneously to satisfy a single query. Instead of building one compound index that covers all filter fields, MongoDB scans multiple indexes independently, then takes the intersection of their matching document IDs. It sounds convenient, but in practice it is rarely as fast as a well-designed compound index.

How Index Intersection Works Internally

When MongoDB considers intersecting indexes, the query planner: 1) Scans index A for documents matching condition 1 and collects their record IDs. 2) Scans index B for documents matching condition 2. 3) Computes the intersection of the two ID sets. 4) Fetches the actual documents using those IDs. This is called an AND_SORTED or AND_HASH stage in explain() output.

// With two single-field indexes:
db.orders.createIndex({ status: 1 })
db.orders.createIndex({ customerId: 1 })

// Query may intersect both indexes
db.orders.find({ status: 'pending', customerId: 'c001' })
  .explain('executionStats')
// Look for 'AND_SORTED' or 'AND_HASH' stage in winningPlan

When MongoDB Chooses Intersection

MongoDB uses index intersection only when its query planner calculates that it is cheaper than alternatives. The planner runs up to 200 candidate plans in parallel (using trial execution) and picks the one with the lowest estimated cost. Intersection is more likely to be chosen when the collection is large and each individual index is highly selective — both narrow the candidate set dramatically before the intersection step.

// Check if MongoDB chose to intersect indexes
const plan = db.orders.find({
  status: 'pending',
  customerId: 'c001'
}).explain('executionStats')

// Intersection chosen:
print(JSON.stringify(plan.queryPlanner.winningPlan, null, 2))
// Look for: 'stage': 'AND_SORTED'

Compound Index vs Intersection: Key Difference

A compound index stores keys from multiple fields in a single, pre-sorted B-tree. A query on those fields does a single, efficient index scan and returns documents in sorted order. Index intersection does multiple separate scans and then merges the results in memory. The merge step adds CPU and memory overhead that a compound index avoids entirely.

// Compound index: one scan, sorted output
db.orders.createIndex({ status: 1, customerId: 1 })

// Single scan: fast, no in-memory merge
db.orders.find({ status: 'pending', customerId: 'c001' })
// explain(): IXSCAN stage only — no AND_SORTED

Compound Indexes Win on Sort

Index intersection cannot satisfy a sort — the merged result set is not in any particular order relative to the sort key, so MongoDB must perform an in-memory SORT stage. A compound index that includes the sort field delivers results in order directly from the index, avoiding the sort overhead entirely. For queries that both filter and sort, a compound index almost always wins.

// Index intersection + sort = in-memory sort required
db.orders.find({ status: 'pending', customerId: 'c001' })
  .sort({ createdAt: 1 })
// Even if both status and customerId indexes intersect,
// MongoDB must still sort the merged result in memory

// Compound index avoids the sort stage
db.orders.createIndex({ status: 1, customerId: 1, createdAt: 1 })

When Intersection Can Outperform Compound

Index intersection occasionally beats a compound index when: 1) Both individual indexes are highly selective (each returns very few documents). 2) The query is ad-hoc — you cannot predict which fields will be filtered together so building a compound index for every combination is impractical. 3) The collection is write-heavy — fewer indexes means lower write overhead, so using intersection from two existing indexes avoids adding a third.

Controlling the Query Planner With hint()

You can force MongoDB to use a specific index (or intersection strategy) with .hint(). This bypasses the query planner's automatic selection and is useful for benchmarking — you can compare the execution stats of your manually chosen compound index versus what the planner would do with individual indexes.

// Force a specific compound index
db.orders.find({ status: 'pending', customerId: 'c001' })
  .hint({ status: 1, customerId: 1 })
  .explain('executionStats')

// Force use of a single-field index (no intersection)
db.orders.find({ status: 'pending', customerId: 'c001' })
  .hint({ status: 1 })
  .explain('executionStats')

Detecting Intersection in explain() Output

When MongoDB uses index intersection, the explain() output shows an AND_SORTED or AND_HASH stage as the parent of two IXSCAN stages. AND_SORTED is used when both indexes return results in the same sorted order; AND_HASH builds an in-memory hash of one result set and probes it with the other. Both are signs that a well-chosen compound index could be faster.

// Identify intersection usage
const plan = db.orders
  .find({ status: 'pending', region: 'EU' })
  .explain('executionStats')

// Check for AND_SORTED or AND_HASH
// If found, benchmark against a compound index { status:1, region:1 }

The General Rule: Prefer Compound Indexes

For known, repeated query patterns, a compound index is almost always faster than relying on intersection. The only reasons to prefer intersection are: queries are too unpredictable to cover with compound indexes, or write throughput is so high that adding more indexes is too costly. In those cases, keep individual indexes lean and let the planner intersect when it helps.

Index Audit: Removing Redundant Indexes

As applications evolve, developers add indexes reactively. Over time, collections accumulate redundant indexes that slow writes without benefiting reads. Review regularly using $indexStats: any index with zero accesses.ops over a long period is unused and can be dropped. Also look for indexes made redundant by the compound prefix rule.

// Identify unused indexes
db.orders.aggregate([{ $indexStats: {} }])
// { name: 'status_1', accesses: { ops: 0, since: ... } }
// If ops is 0 since a long time, the index is unused — drop it

db.orders.dropIndex('status_1')

Practical Guidance: A Decision Framework

Use this framework: Query pattern is known and repeated? → Build a compound index using ESR. Query is ad-hoc or hard to predict? → Rely on individual indexes and accept possible intersection. Write throughput is critical? → Minimise total index count; remove unused indexes. Query involves a sort? → Always use a compound index; intersection never satisfies sorts.

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

In this lesson you learned: index intersection uses two single-field indexes and merges their results in memory, adding overhead, compound indexes are almost always faster for known, repeated query patterns — especially those with sorts, and use $indexStats to find and remove unused or redundant indexes that slow writes. Next up we explore aggregation pipeline optimization tips.

자주 묻는 질문

“인덱스 교차와 복합 인덱스 비교” 강의는 무료인가요?

네 — “인덱스 교차와 복합 인덱스 비교” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“인덱스 교차와 복합 인덱스 비교”에서 뭘 배우나요?

학습자는 MongoDB가 여러 단일 필드 인덱스를 교차 사용하는 경우와 복합 인덱스가 교차보다 우수한 경우를 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“인덱스 교차와 복합 인덱스 비교” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 데이터베이스 프로파일러와 느린 쿼리 로그
  2. 복합 인덱스 접두사 규칙과 ESR 원칙
  3. 인덱스 교차와 복합 인덱스 비교
  4. 집계 파이프라인 최적화 팁
← MongoDB Academy(으)로 돌아가기