Working with Specialized Indexes

1. Creating Hashed Index

FormUse
createIndex({userId: "hashed"})Hashed shard key candidate
Equality onlyNo range queries
No multikeyArray fields not allowed

2. Creating Wildcard Index

FormEffect
createIndex({"$**": 1})Index every field
createIndex({"meta.$**": 1})Subtree index
wildcardProjectionInclude / exclude specific paths
UseVariable / unknown schema

3. Creating TTL Index

FormBehavior
createIndex({expireAt:1}, {expireAfterSeconds:0})Expires at the Date value
{createdAt:1}, {expireAfterSeconds:3600}1 hour after createdAt

4. Creating Partial Index

AspectDetail
OptionpartialFilterExpression: {...}
Operators allowed$eq, $gt, $gte, $lt, $lte, $exists, $type, $and, $or, $in
BenefitSmaller index; covers only relevant docs
Query must matchFilter expression must logically include the partial condition
db.orders.createIndex(
  { customerId: 1, createdAt: -1 },
  { partialFilterExpression: { status: "active" } }
);

5. Creating Case-Insensitive Index

AspectDetail
Optioncollation: { locale: "en", strength: 2 }
Strength 2Case-insensitive comparisons
QueryMust use same collation to use index

6. Creating Hidden Index

OptionEffect
hidden: truePlanner ignores; unique/TTL still enforced
Use caseTest impact of drop without losing rebuild cost

7. Unhiding Index

CommandEffect
collMod({index: {name: "idx", hidden: false}})Re-expose to planner

8. Understanding Specialized Index Use Cases

IndexBest For
HashedEven shard distribution
WildcardUnknown/dynamic field shapes
TTLSession / cache expiration
PartialHot subset of large collection
CollatedCase-insensitive uniqueness
HiddenPre-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