liveBook · Manning

Partial index

As explained in MongoDB 8.0 in Action, Third Edition

A partial index indexes only documents that satisfy a specified filter expression.

A partial index indexes only documents that satisfy a specified filter expression. By indexing a subset of a collection, it reduces storage requirements and the cost of index creation and maintenance. section 7.4.1

Create a partial index with these practical steps:

  • Choose the indexed fields and the subset of documents that should receive index entries. section 7.4.1
  • Call db.collection.createIndex() and provide the condition through partialFilterExpression. section 7.4.1
  • Use supported filter operators such as equality, $exists, comparison operators, $type, $and, $or, and $in. section 7.4.1

Index movie documents

A compound index on year, type, and imdb.rating can be restricted to documents whose type equals "movie". This keeps non-movie documents out of the index while preserving the selected fields for indexed movie documents. section 7.4.1

db.getSiblingDB('sample_mflix').movies.createIndex(
    {
        year: 1,
        type: 1,
        "imdb.rating": 1
    },
    {
        partialFilterExpression: { type: { $eq: "movie" } }
    } // Creates a partial index on the movies collection
➥for documents where type is "movie"
)

Run the mongosh command to create the filtered compound index on sample_mflix.movies. section 7.4.1

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Defines filtered indexing, explains supported operators and cost benefits, and demonstrates one compound example without deeper planner analysis.
Examples
Uses a movies collection index on year, type, and imdb.rating filtered to documents where type equals "movie".
What it assumes
Assumes familiarity with MongoDB collections and indexes while teaching the partialFilterExpression option from its purpose and syntax.
What you can do after
Apply it via db.collection.createIndex() with indexed fields and a partialFilterExpression.
How it connects
Connects partial indexes with compound indexes, sparse indexes, TTL indexes, and query-planner index selection.

Also explained in

Compare how 2 books explain partial index →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.