🍃 MongoDB Intermediate

What are multikey indexes in MongoDB?

Why Interviewers Ask This

Mid-level MongoDB roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

Multikey indexes are automatically created by MongoDB when you create an index on a field that contains an array value. MongoDB creates separate index entries for each element in the array, allowing efficient queries for any element in the array. Automatic creation: db.products.createIndex({ tags: 1 }) — if tags is an array like ["electronics", "portable", "wireless"], MongoDB creates 3 index entries, one for each tag. Query: db.products.find({ tags: "electronics" }) uses the multikey index efficiently. Array element queries: equality (find docs where array contains value), $all (contains all specified values), $elemMatch (at least one element matches all conditions), $size (array has N elements). Compound multikey index restrictions: a compound index can have at most ONE array field. You cannot create a compound index on two fields that both contain arrays for the same document — this would create an exponential number of index entries. Covered queries with multikey: multikey indexes cannot fully cover a query — MongoDB must still access the document to return data (even if all projected fields are in the index) because array membership queries need document verification. Index size consideration: a document with a 1,000-element array creates 1,000 index entries — can significantly increase index size and write overhead. Consider whether indexing array fields is worth the cost. Embedded document arrays: db.orders.createIndex({ "items.productId": 1 }) — creates a multikey index on the productId field within each array element of "items."

Common Mistake

A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.