Working with Specialized Indexes
1. Creating Hashed Index
| Form | Use |
|---|---|
createIndex({userId: "hashed"}) | Hashed shard key candidate |
| Equality only | No range queries |
| No multikey | Array fields not allowed |
2. Creating Wildcard Index
| Form | Effect |
|---|---|
createIndex({"$**": 1}) | Index every field |
createIndex({"meta.$**": 1}) | Subtree index |
| wildcardProjection | Include / exclude specific paths |
| Use | Variable / unknown schema |
3. Creating TTL Index
| Form | Behavior |
|---|---|
createIndex({expireAt:1}, {expireAfterSeconds:0}) | Expires at the Date value |
{createdAt:1}, {expireAfterSeconds:3600} | 1 hour after createdAt |
4. Creating Partial Index
| Aspect | Detail |
|---|---|
| Option | partialFilterExpression: {...} |
| Operators allowed | $eq, $gt, $gte, $lt, $lte, $exists, $type, $and, $or, $in |
| Benefit | Smaller index; covers only relevant docs |
| Query must match | Filter expression must logically include the partial condition |
db.orders.createIndex(
{ customerId: 1, createdAt: -1 },
{ partialFilterExpression: { status: "active" } }
);
5. Creating Case-Insensitive Index
| Aspect | Detail |
|---|---|
| Option | collation: { locale: "en", strength: 2 } |
| Strength 2 | Case-insensitive comparisons |
| Query | Must use same collation to use index |
6. Creating Hidden Index
| Option | Effect |
|---|---|
| hidden: true | Planner ignores; unique/TTL still enforced |
| Use case | Test impact of drop without losing rebuild cost |
7. Unhiding Index
| Command | Effect |
|---|---|
collMod({index: {name: "idx", hidden: false}}) | Re-expose to planner |
8. Understanding Specialized Index Use Cases
| Index | Best For |
|---|---|
| Hashed | Even shard distribution |
| Wildcard | Unknown/dynamic field shapes |
| TTL | Session / cache expiration |
| Partial | Hot subset of large collection |
| Collated | Case-insensitive uniqueness |
| Hidden | Pre-drop validation |
9. Choosing Right Index Type
Query Pattern
├─ Equality only on high-cardinality → Hashed
├─ Range / sort / equality → Single or Compound B-tree
├─ Array contains → Multikey (auto)
├─ Unknown fields → Wildcard
├─ Hot subset only → Partial
├─ Text search → Text (or Atlas Search)
├─ Location → 2dsphere
└─ Auto-expire docs → TTL