What are indexes in MongoDB and why are they important?
An index is a separate B-tree data structure that lets MongoDB find documents without scanning the whole collection. Trades disk + write speed for read speed.
_id index — created automatically and cannot be dropped.
Single-field — one column;
createIndex({ field: 1 })ascending or-1descending.Compound — multiple fields; serves queries on the leftmost prefix.
Multikey — auto-built when indexing an array field.
Special types — text, geospatial (2d/2dsphere), hashed, wildcard, TTL.
Cost — slows writes and uses RAM/disk; index only what you query.
// Create single field index
db.users.createIndex({ email: 1 }); // 1 = ascending
// Compound index (order matters for queries)
db.orders.createIndex({ userId: 1, createdAt: -1 }); // -1 = descending
// Unique index (enforces uniqueness)
db.users.createIndex({ email: 1 }, { unique: true });
// TTL index (auto-delete expired documents)
db.sessions.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 });
// Text index (full-text search)
db.articles.createIndex({ title: 'text', body: 'text' });
db.articles.find({ $text: { $search: 'mongodb tutorial' } });
// Explain query execution plan
db.users.find({ email: 'john@test.com' }).explain('executionStats');
// Shows: IXSCAN (index used) vs COLLSCAN (no index — slow!)
// List and drop indexes
db.users.getIndexes();
db.users.dropIndex('email_1');createIndex creates a B-tree index. Compound indexes support queries using the indexed fields in order (left-to-right prefix). Unique indexes prevent duplicate values.
TTL indexes auto-delete documents when the time field exceeds expireAfterSeconds. Text indexes enable $text search. explain() shows whether the query uses an index (IXSCAN) or scans all documents (COLLSCAN).
Know index types: single, compound, multikey, text, TTL, geospatial, hashed. explain() is the key debugging tool (IXSCAN=good, COLLSCAN=bad). Compound index field order matters (supports queries using left-to-right prefix).
TTL for auto-expiring sessions/caches. Unique for email/username constraints.