9. Multikey Indexes for Arrays

When an index is created on an array field, MongoDB creates a multikey index. Multikey indexes support queries that match array elements and are common in schemas containing tags, categories, and embedded records.

For example, an index on tags can support eligible queries that search for a specific tag. If an array contains several values, the index can contain multiple entries for a document.

Compound multikey indexes have important restrictions. In particular, a compound multikey index cannot index more than one independently array-valued indexed field in the same document. Array query semantics also matter: matching multiple predicates against one array element may require $elemMatch.

Multikey indexes can grow significantly when arrays contain many elements. Measure index size and write costs for large arrays.

Code Example
db.articles.createIndex({ tags: 1 });

db.articles.find({ tags: "mongodb" }).explain("executionStats");
Key Takeaways
  • Indexes on array fields become multikey indexes.
  • Array indexes can support matching array elements.
  • Compound multikey indexes have restrictions.
  • Large arrays can increase index size and write cost.
Knowledge Check

What type of index does MongoDB create when an indexed field contains arrays?