0
0
MongodbConceptBeginner · 3 min read

Partial Index in MongoDB: What It Is and How It Works

A partial index in MongoDB is an index that only includes documents matching a specified filter condition. It helps improve query performance and reduce index size by indexing only relevant documents instead of the entire collection.
⚙️

How It Works

Imagine you have a large collection of documents, but you only often query a small subset of them based on a condition, like documents where a field "status" is "active". Creating a full index on the entire collection wastes space and slows down writes because it indexes every document.

A partial index solves this by indexing only the documents that meet a filter condition you specify. It's like having a special phone book that only lists people who live in a certain city, making it faster to find them without flipping through everyone.

When you run a query that matches the filter condition, MongoDB uses the partial index to quickly find results. Queries that don't match the filter won't use this index, so it stays efficient and small.

💻

Example

This example creates a partial index on the "users" collection that only indexes documents where the "status" field is "active".

mongodb
db.users.createIndex(
  { lastLogin: 1 },
  { partialFilterExpression: { status: "active" } }
);

// Query that can use the partial index
db.users.find({ status: "active", lastLogin: { $gte: new Date("2024-01-01") } });
Output
Index created with partial filter on { status: "active" } Query uses partial index to efficiently find active users who logged in after 2024-01-01
🎯

When to Use

Use partial indexes when you frequently query a subset of documents defined by a condition, and you want to save space and improve performance. For example:

  • Indexing only active users in a large user collection.
  • Indexing documents with a specific status or flag.
  • Optimizing queries on sparse data where many documents don't have the indexed field.

This reduces index size and speeds up queries that match the filter, while avoiding overhead on irrelevant documents.

Key Points

  • Partial indexes index only documents matching a filter condition.
  • They reduce index size and improve write performance.
  • Queries must match the filter condition to use the partial index.
  • Useful for indexing subsets like active users or flagged items.

Key Takeaways

Partial indexes index only documents that meet a specified filter condition.
They save space and speed up queries on filtered subsets of data.
Queries outside the filter condition do not use the partial index.
Ideal for collections with many documents but queries targeting a small subset.
Creating partial indexes improves write performance by indexing fewer documents.