What are indexes in MongoDB?

Why Interviewers Ask This

This is a classic screening question for MongoDB roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.

Answer

Indexes in MongoDB improve query performance by allowing the database to find documents without a full collection scan. Without an index, MongoDB must scan every document (COLLSCAN). With an index, it can quickly jump to matching documents (IXSCAN). Default index: every collection has an index on _id automatically. Creating indexes: db.users.createIndex({ email: 1 }) — single field index, ascending (1); db.users.createIndex({ email: -1 }) — descending; db.users.createIndex({ lastName: 1, firstName: 1 }) — compound index (multiple fields). Index types: Single field: on one field; Compound: multiple fields — order matters (leftmost prefix rule); Multikey: automatically created when indexing array fields — one index entry per array element; Text: for full-text search; 2dsphere: for GeoJSON geospatial; Hashed: for hash-based sharding; Wildcard: indexes all fields or a subset dynamically. Index options: unique: true — enforces uniqueness; sparse: true — only indexes documents that contain the field; expireAfterSeconds — TTL index; background: true (legacy) — build without blocking. View indexes: db.users.getIndexes(). Drop index: db.users.dropIndex("email_1"). Indexes trade write performance for read performance — don't over-index.

Pro Tip

This topic has MongoDB-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.