On this page
  1. Indexes, Replica Sets & Transactions
  2. Contents
  3. The ESR Compound Index Rule & Specialized Indexes
  4. Inspecting Plans (explain("executionStats"))
  5. Replica Sets, Read/Write Concerns & Multi-Document Transactions

Indexes, Replica Sets & Transactions

Prev: CRUD & Aggregation Pipeline | Up: mongodb | Next: index
Rel: Indexing & Storage Engines, CAP, PACELC & Consistency Models
Ref: MongoDB — The ESR Guideline
Tags: #public #databases #mongodb #nosql #indexing #transactions


Contents


The ESR Compound Index Rule & Specialized Indexes

Order compound index keys as Equality -> Sort -> Range to avoid in-memory sorts and minimize scanned keys:

// Supports: find({ status: "paid", totalCents: { $gte: 5000 } }).sort({ createdAt: -1 })
db.orders.createIndex({ status: 1, createdAt: -1, totalCents: 1 });

// TTL index: automatically expire session documents after 24h
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 86400 });

MongoDB also supports multikey indexes (indexing array elements automatically) and partial indexes (partialFilterExpression).


Inspecting Plans (explain("executionStats"))

Check winningPlan.stage (IXSCAN vs. COLLSCAN), totalKeysExamined, and totalDocsExamined — aim for totalDocsExamined close to nReturned.


Replica Sets, Read/Write Concerns & Multi-Document Transactions

Linked from

Related notes