What is a sparse index in MongoDB?
Why Interviewers Ask This
Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid MongoDB basics — a prerequisite for any developer role.
Answer
A sparse index only contains entries for documents that have the indexed field, even if the value is null — it ignores documents where the field is absent. This is different from the default (dense) index that includes all documents, storing null for documents without the field. Creating a sparse index: db.users.createIndex({ phone: 1 }, { sparse: true }). Why use sparse indexes: (1) Space efficiency: if only 10% of documents have a "phone" field, a sparse index stores only 10% of the entries vs a full index; (2) Unique + sparse: a unique sparse index allows multiple documents to lack the field (they're not in the index) while still enforcing uniqueness among documents that DO have the field. This is common for "optional unique" fields like phone numbers; (3) Selective queries: queries that filter for documents where the field exists benefit from sparse indexes. Caveat: if a query doesn't explicitly filter for the indexed field, MongoDB may not use the sparse index (it would miss documents lacking the field). For example, db.users.find({}).sort({ phone: 1 }) might COLLSCAN instead of using the sparse index, as sorting with the sparse index would exclude documents without "phone." Partial indexes (MongoDB 3.2+) are more powerful: db.users.createIndex({ phone: 1 }, { partialFilterExpression: { phone: { $exists: true } } }) — explicitly define which documents to include, with full support for any filter expression.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex MongoDB answers easy to follow.