Working with Multikey Indexes
1. Creating Multikey Index
| Aspect | Detail |
|---|---|
| Trigger | Indexing a field whose value is an array |
| Form | createIndex({tags: 1}) where tags is array |
| Auto-detected | Marked multikey on first array doc |
2. Understanding Multikey Behavior
| Aspect | Detail |
|---|---|
| Index entries | One per array element per doc |
| Size cost | Proportional to total array elements |
| Cannot cover | Queries projecting array field |
| Multikey marker | Stored on index; cleared only by rebuild |
3. Indexing Array of Scalars
| Aspect | Detail |
|---|---|
| Pattern | {tags: ["a","b","c"]} |
| Index | 3 entries: "a","b","c" → docId |
| Query | {tags: "a"} uses index |
4. Indexing Array of Documents
| Pattern | Index Form |
|---|---|
items: [{sku, qty}] | createIndex({"items.sku": 1}) |
| Match | Use $elemMatch for per-element conditions |
5. Understanding Multikey Limitations
| Limitation | Detail |
|---|---|
| Hashed multikey | Not allowed |
| Shard key | Cannot be a multikey index |
| Coverage | Cannot cover queries with array projection |
| Sort | Cannot sort by multikey field on array |
6. Using Compound Multikey Indexes
| Rule | Detail |
|---|---|
| At most one array key | Only one indexed field may be an array per doc |
| Violation | WriteError on insert/update |
7. Avoiding Multiple Multikey Fields
| Workaround | Strategy |
|---|---|
| Pre-compute | Store flattened scalar fields |
| Separate indexes | Two single-field indexes |
| Wildcard index | For variable-shape docs |
8. Analyzing Multikey Index Usage
| Tool | Output |
|---|---|
| explain.queryPlanner.winningPlan.inputStage.isMultiKey | true / false |
| multiKeyPaths | Which paths were multikey |
| $indexStats | Usage counters |