Mongodb compound index esr rule
Skill kjuhwa/skills-hub/skills/backend/mongodb-compound-index-esr-rule
Self-correcting knowledge corpus for Claude Code — 9 stable shape clusters, bias-correction pipeline baked into contribution flow. 47 papers, 45 techniques, 1.1k skills.
npx -y skills add kjuhwa/skills-hub --skill mongodb-compound-index-esr-ruleAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
One thing to look at
- 0 stars0 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
What its author says it does
Copied from the file, not written here
Order MongoDB compound-index fields as Equality → Sort → Range so the query planner keeps a tight IXSCAN and avoids in-memory sorts.
SKILL.md
2.1 KB, 403 tokens by cl100k_base, as published. Nobody here has run it
MongoDB Compound Index — ESR Rule
Order fields as Equality → Sort → Range.
- Equality — fields filtered with
= - Sort — fields used in
sort() - Range — fields with
<,>,between, or$inover a large set
Why
MongoDB consumes the index left-to-right. Equality fields narrow the scan to a contiguous key range; sort fields let the engine return results without an in-memory sort; range fields expand the scan and must come last — placing them earlier forces a wider scan and may break sort usage.
Steps
- List the query's predicates; classify each field as equality, sort, or range.
- Build the index in ESR order. Drop fields that don't participate.
- Remove dead indexes whose key prefix is covered by the new one (left-prefix rule).
- Verify with
db.<coll>.find(...).explain("executionStats"): wantIXSCANandnReturned ≈ totalDocsExamined, with noSORTstage.
Example
@CompoundIndexes({
@CompoundIndex(name = "tenant_service_time",
def = "{tenantId:1, serviceId:1, startTime:-1, duration:1}")
// E: tenantId, serviceId S: startTime (desc) R: duration
})
Counter / Caveats
- Sort direction: MongoDB can scan an index backwards, so an ASC query on a DESC index still works — position matters more than direction.
$inwith a small list behaves like equality; large$inlists are range-like.- Partial indexes and
hint()can invalidate this reasoning — always re-check withexplain(). - A compound index satisfying ESR for one query may be wrong for a sibling query — index per workload, not per table.
What ships with it
Read from the repository
Just SKILL.md. No reference files, no scripts.