MongoDB Multikey Indexes automatically index array fields to speed up queries on individual elements within arrays, improving performance for datasets with nested or list-based values.
- Automatically indexes array fields and each element within the array.
- Improves query performance for queries targeting elements within array fields.
- Enables efficient lookups on individual values inside arrays.
Create a Multikey Index
When an index is created on an array field, MongoDB generates separate index entries for each array element, enabling efficient equality and membership queries as well as index-supported sorting on array values.
Syntax:
db.Collection_name.createIndex({field_name: 1/ -1})Examples of MongoDB Multikey Indexes
In the following example, we are working with:
- Database: gfg
- Collections: student
- Document: Two documents contain the details of the students

Example 1: Index Basic Arrays
Create multi-index with the help of createIndex() method on the field language:
db.student.createIndex({language:1})Output:

Check the index using the getIndexes() method:

Example 2: Index Arrays with Embedded Documents
Create a multikey index on an array field that contains nested documents/objects.
db.student.createIndex({"details.age":1, "details.branch":1})Output:

Check the index using the getIndexes() method:

Limitations of MongoDB Multikey Indexes
While MongoDB multikey indexes offer significant performance improvements, they come with some limitations and constraints:
- Compound Multikey Restriction: Only one indexed field per document can be an array in a compound multikey index.
- Shard Key Limitation: Array fields (multikey indexes) cannot be used as shard keys.
- $expr Limitation: Multikey indexes are not used to support $expr-based queries.
- Insertion Constraint: Inserts that violate multikey rules (multiple array fields) are rejected.
Important Points of MongoDB Multikey Indexes
Here are some important point discussed:
- Multikey indexes index array fields and their elements to improve query performance on array data.
- Multikey indexes cannot be used as shard key indexes.
- Hashed indexes are not multikey indexes in MongoDB.
- Multikey indexes do not support $expr-based queries.
- When a query matches an entire array value, MongoDB scans the multikey index entries for the array elements to evaluate the match.