Working with Multikey Indexes

1. Creating Multikey Index

AspectDetail
TriggerIndexing a field whose value is an array
FormcreateIndex({tags: 1}) where tags is array
Auto-detectedMarked multikey on first array doc

2. Understanding Multikey Behavior

AspectDetail
Index entriesOne per array element per doc
Size costProportional to total array elements
Cannot coverQueries projecting array field
Multikey markerStored on index; cleared only by rebuild

3. Indexing Array of Scalars

AspectDetail
Pattern{tags: ["a","b","c"]}
Index3 entries: "a","b","c" → docId
Query{tags: "a"} uses index

4. Indexing Array of Documents

PatternIndex Form
items: [{sku, qty}]createIndex({"items.sku": 1})
MatchUse $elemMatch for per-element conditions

5. Understanding Multikey Limitations

LimitationDetail
Hashed multikeyNot allowed
Shard keyCannot be a multikey index
CoverageCannot cover queries with array projection
SortCannot sort by multikey field on array

6. Using Compound Multikey Indexes

RuleDetail
At most one array keyOnly one indexed field may be an array per doc
ViolationWriteError on insert/update

7. Avoiding Multiple Multikey Fields

WorkaroundStrategy
Pre-computeStore flattened scalar fields
Separate indexesTwo single-field indexes
Wildcard indexFor variable-shape docs

8. Analyzing Multikey Index Usage

ToolOutput
explain.queryPlanner.winningPlan.inputStage.isMultiKeytrue / false
multiKeyPathsWhich paths were multikey
$indexStatsUsage counters