Partial Index in MongoDB: What It Is and How It Works
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".
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") } });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.