16. Selectivity, Cardinality, and Query Shape
Selectivity describes how much a predicate narrows the candidate set. A highly selective condition matches a small fraction of documents; a low-selectivity condition matches many documents.
A filter such as a unique identifier is typically highly selective. A boolean field such as active may be less selective if most records share the same value. Low selectivity does not automatically make an index useless: the index may still help with sorting, coverage, or combined predicates.
Cardinality describes how many distinct values a field has. High-cardinality fields often distinguish records more precisely, but cardinality alone does not determine whether an index is beneficial.
Evaluate the complete query shape: equality predicates, ranges, sort, projection, result limit, and data distribution. Use explain statistics and real workload measurements.
db.orders.find({ _id: 1001 }).explain("executionStats");
db.orders.find({ status: "delivered" }).explain("executionStats");- Selectivity measures how much a predicate narrows candidates.
- Cardinality is the number of distinct values.
- Low-selectivity indexes can still be useful in some query shapes.
- Judge indexes using full query behavior and execution evidence.
What does a highly selective predicate generally do?