A multikey index in MongoDB is automatically created when indexing an array field, storing each array element as a separate index key pointing back to the parent document.
A multikey index is MongoDB's mechanism for indexing array fields. When you create an index on a field that contains an array, MongoDB automatically creates a multikey index . Instead of indexing the array as a whole, it creates a separate index key for every element in the array, each pointing back to the original document . This enables efficient queries that look for documents containing specific values within an array.
Under the hood, a multikey index is a B-tree structure similar to regular indexes, but with multiple entries per document. For example, consider a document with tags: ["moon", "apollo", "spaceflight", "nasa"]. A multikey index on the tags field creates four separate index entries, each mapping one tag value to the document . This allows MongoDB to quickly locate documents containing a specific tag without scanning every document.
If you index an array of 1,000 elements, MongoDB will create 1,000 separate index keys for that single document . This has significant performance implications:
Multikey indexes have several important limitations that become critical when dealing with large arrays:
MongoDB applies special rules when computing index boundaries for multikey indexes . When a query uses $elemMatch, MongoDB can intersect boundaries for multiple conditions on the same array field, producing tighter index ranges and better performance . However, without $elemMatch, MongoDB cannot intersect boundaries and must choose one condition's bounds to scan .
For unique multikey indexes, the uniqueness constraint applies across documents, not within a single document . This means a single document can have multiple array elements with the same value (e.g., an array containing the same tag multiple times) without violating uniqueness, as long as no other document contains that value.
Indexing an array of 1,000 elements is feasible if you understand the trade-offs. The key considerations are: