Skip to content
LESSON 25 / 50Intermediateindexing

Partial & Sparse Indexes: Saving RAM on Skewed Data

Partial and Sparse indexes index only documents matching a filter expression or containing a target field, slashing index RAM footprint by up to 95%.

Interactive Engine Simulator

Index Traversal & IXSCAN vs COLLSCAN Execution Plan

Topic 25: Partial & Sparse Indexes: Saving RAM on Skewed Data

Execution Stage
IXSCAN + FETCH
B-Tree leaf seek
Documents Examined
2
O(log N) lookup
Keys Examined
2
Index keys inspected
Query Latency
0.3 ms
WiredTiger execution time
Explain Plan Output Summary:
{
  "queryPlanner": {
    "winningPlan": {
      "stage": "FETCH",
      "inputStage": {
        "stage": "IXSCAN",
        "indexName": "role_1_country_1",
        "isMultiKey": false,
        "direction": "forward"
      }
    }
  },
  "executionStats": {
    "nReturned": 2,
    "executionTimeMillis": 1,
    "totalKeysExamined": 2,
    "totalDocsExamined": 2
  }
}

1. Formal Definition & Architecture Intent

A Partial Index only indexes documents in a collection that meet a specified filter expression (partialFilterExpression). A Sparse Index only indexes documents that contain the indexed field. Partial indexes supersede sparse indexes by offering expressive filtering operators ($gt, $exists, $type).

2. Explain Like I'm 5 (Mental Model)

Instead of making an index entry for all 1,000,000 orders, you create a VIP index that only entries for orders where total > $1,000. The index is 99% smaller and super fast.

3. Real-World Architecture Example

Indexing only active users with verified email addresses.

Sample BSON Documents:
Collection: db.users
{
  "email": "verified_user@cloud.io",
  "status": "active"
}

Only 5% of users are verified; indexing only active users saves 95% of index RAM.

4. MQL Implementation Steps

Step 1: Create a partial index with filter expression
db.users.createIndex(
  { email: 1 },
  {
    unique: true,
    partialFilterExpression: { status: "active", email: { $exists: true } }
  }
);
Enforces unique email ONLY on active accounts, allowing multiple inactive dummy accounts!
Step 2: Query that utilizes the partial index
db.users.find({ email: "verified_user@cloud.io", status: "active" });
Query filter must match or be a subset of the partialFilterExpression.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
Subset RequirementA query can only use a partial index if its WHERE criteria guarantees the result is a subset of the partialFilterExpression.
Sparse vs PartialSparse indexes only check field existence; Partial indexes allow complex expressions ($gt, $eq, $exists).

6. Deep Dive: Unique Constraints on Partial Indexes

In many business domains, uniqueness is only required for active records. For example, a username must be unique among active accounts, but deleted accounts can retain duplicate historic usernames. A unique partial index cleanly solves this without application-level workarounds.

// Unique constraint scoped only to un-deleted accounts:
db.accounts.createIndex(
  { username: 1 },
  { unique: true, partialFilterExpression: { deleted: false } }
);
Production Warning: If a query omits the filter condition, MongoDB cannot use the partial index and falls back to a COLLSCAN.

7. Architectural Trade-offs

Advantages
  • •Reduces index size by up to 95% for skewed or status-filtered datasets
  • •Faster write operations: inserts for non-matching documents bypass index updates
  • •Enables conditional unique constraints on subsets of data
Disadvantages & Gotchas
  • •Queries that do not include the partial filter predicate cannot use the index
  • •Cannot be combined with sparse option in the same index

8. Technical Interview Questions

Q1: Why are Partial Indexes preferred over Sparse Indexes in modern MongoDB architecture?

Sparse indexes only filter on field existence ({ field: { $exists: true } }), whereas Partial Indexes support expressive filter predicates (e.g. { rating: { $gte: 4 }, status: "active" }). In fact, sparse indexes are essentially a subset of partial indexes.

9. Staff-Level Ready Answer

"Partial indexes index only documents satisfying a partialFilterExpression. They drastically cut RAM usage and write overhead on skewed data and enable conditional unique constraints. The query planner will only use a partial index if the query predicate is guaranteed to be a subset of the index filter."

10. Quick Knowledge Check

Under what condition will the query planner refuse to use a Partial Index on { email: 1 } created with partialFilterExpression: { status: "active" }?