Indexing StrategiesBeginner
1Question 1 of 1
javascriptWhat types of indexes does MongoDB support and how do Compound Indexes work?
Explanation & Concept
MongoDB supports single-field indexes, compound indexes, multikey indexes (for arrays), text indexes, geospatial indexes, and TTL (time-to-live) indexes.
A **Compound Index** indexes multiple fields together. Query performance follows the **Equality, Sort, Range (ESR)** rule: place exact equality fields first, sorting fields second, and range filters last.
Code Example
javascript
// Create a compound index on tenantId (equality), status (equality), and createdAt (range/sort)
db.tickets.createIndex(
{ tenantId: 1, status: 1, createdAt: -1 },
{ name: "idx_tenant_status_date" }
);
// This query performs a fast index seek without sorting in RAM:
db.tickets.find({
tenantId: "org_123",
status: "OPEN",
createdAt: { $gte: new Date("2026-01-01") }
}).sort({ createdAt: -1 });How It Works & Key Takeaways
By structuring the index following ESR, MongoDB evaluates the query purely through B-Tree traversal and returns rows already in the desired sort order.
Mock Test · 1 Questions · Optional
Ready for CRUD Operations?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner1 questions