MongoDB Index Type

Compound Indexes in MongoDB: How It Works and When to Use It

Sorts by each declared field in sequence; field order controls usable prefixes, ranges, and sort directions.

What Is a Compound Indexes in MongoDB?

Sorts by each declared field in sequence; field order controls usable prefixes, ranges, and sort directions.

How the Compound Indexes Algorithm Works

Sorts by each declared field in sequence; field order controls usable prefixes, ranges, and sort directions.

Diagram showing the Compound Indexes lookup algorithm
Conceptual Compound Indexes algorithm. Exact behavior depends on the database version and query plan.

When to Use Compound Indexes

Repeated filter and sort combinations designed around equality, sort, and range needs.

How to Create a MongoDB Compound Indexes

Review data quality, existing structures, feature support, build time, and deployment requirements before creating an index on a production table.

db.orders.createIndex({ customerId: 1, createdAt: -1 })

Compound Indexes Query Example

This example demonstrates the matching query shape. Check the execution plan to confirm that the engine can use the index.

db.orders.find({ customerId: 42 }).sort({ createdAt: -1 }).limit(20)

Queries Supported by Compound Indexes

Repeated filter and sort combinations designed around equality, sort, and range needs. A similar-looking predicate may not use the same access path; operators, expressions, key order, and data type all matter.

Read Performance, Storage, and Write Costs

Larger keys add storage and write amplification; a wrong order can make the index unusable for important queries. Indexes reduce some search work but require storage and add maintenance to writes.

Compound Indexes Limitations and Common Mistakes

Queries skipping leading fields generally cannot use the index as an efficient prefix.

Do not assume that an index being present means the optimizer chose it or that the query became selective.

How to Measure and Tune Compound Indexes

Use explain with the exact filter and sort; review index prefixes before adding more indexes.

Compare representative plans and timings before and after, including concurrent writes and realistic data volumes.

Compound Indexes Questions

Will the database always use this index?

No. The optimizer weighs selectivity, estimated costs, statistics, cache state, and the amount of data returned.

What should I verify before production?

Confirm version support, query compatibility, write overhead, build/rollback procedures, and index behavior during backup and recovery.

Official MongoDB Index Documentation

Check MongoDB documentation: Index Types for release-specific requirements and supported operators.