liveBook · Manning

Composite index

As explained in MongoDB 8.0 in Action, Third Edition

A compound index is an index whose key consists of multiple document fields.

A composite index, called a compound index in MongoDB, has a key made from multiple document fields. Use one when recurring queries filter or sort on those fields together. Field order matters: an index on year, type, and IMDb rating can support queries starting with year, but not queries on type or rating alone. section 7.2.2

Listing 7.6 Creating a compound index on three fields
db.movies.createIndex(
    { year: 1, type: 1, "imdb.rating": 1 }
)

Create a three-field index for movie searches with db.movies.createIndex({ year: 1, type: 1, "imdb.rating": 1 }). Each 1 specifies ascending order. section 7.2.2

Check the leading fields before relying on that index:

  • A query on year; year and type; or all three fields matches an index prefix. section 7.2.2
  • A query on type or IMDb rating without year does not match a prefix of this index. In the illustrated rating-only query, explain("executionStats") reports a COLLSCAN examining 21,349 documents. section 7.2.2

Index a filter and sort together

For db.movies.find({ year: 1914, "imdb.rating": { $gte: 7 } }).sort({ title: 1 }), create db.movies.createIndex({ year: 1, title: 1, "imdb.rating": 1 }). This places the year filter first, the title sort next, and the rating condition last. The illustrated explain plan uses IXSCAN followed by FETCH; it examines four index keys and returns two documents. section 7.2.2

Compound indexes also support multi-field sorting when sort keys follow their index order: { runtime: 1, year: 1 } supports sorting by runtime and then year, not the reverse. Choose field order from the queries and sorts the application actually runs, then inspect the execution plan rather than assuming an index is used. section 7.6.7 section 7.2.2

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Defines index prefixes, works through creation commands and execution plans, and specifies sort-key order without detailing index storage internals.
Examples
Uses movie indexes on release year, type, IMDb rating, and title, plus theater and runtime sorting queries.
What it assumes
Introduces createIndex syntax while relying on basic familiarity with document fields and find queries.
What you can do after
Build it from scratch with createIndex, align field order with queries and sorts, and check index use with explain("executionStats").
How it connects
Connects index prefixes, query planning, collection scans, index scans, and multi-field sorting.

Also explained in

Compare how 3 books explain composite 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.