Index Types and Strategies
9 min read
Common Index Types
Beyond single-field indexes, MongoDB supports several specialised index types suited to different query patterns.
- Single-field — index on one field (
{ age: 1 }) - Compound — index on multiple fields; field order and sort direction matter
- Multikey — automatically created when the indexed field is an array
- Text — enables full-text search with
$textand$search - TTL (Time-To-Live) — automatically expires documents after a set duration (great for sessions/logs)
js
// Text index for searching student bios
db.students.createIndex({ bio: "text" });
db.students.find({ $text: { $search: "react developer" } });
// TTL index: delete documents 30 days after createdAt
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 2592000 });Indexes speed up reads but slow down writes slightly (the index must be updated on every insert/update/delete). Index only the fields you actually query.
Ready to test yourself?
Practice MongoDB— quiz & coding exercises