You can create an index on a field containing an array value to improve performance for queries on that field. When you create an index on a field containing an array value, MongoDB stores that index as a multikey index.
To create an index, use the db.collection.createIndex() method. Your operation should resemble this prototype:
db.<collection>.createIndex( { <field>: <sortOrder> } )
About this Task
The examples on this page use data from the sample_mflix dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the Sample Dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.
You regularly run a query that returns movies released before 1910 that have the Short genre. You can create an index on the genres field to improve performance for this query.
Warning
Starting in MongoDB 9.0, if an indexed field becomes a multikey field while a query that references the field is running, the query might fail with a QueryKilledError. An indexed field becomes multikey when you insert or update a document so the field contains an array value.
If your query fails with this error, re-run the query after the insert or update operation completes.
Procedure
The following operation creates an ascending multikey index on the genres field of the movies collection:
db.movies.createIndex( { genres: 1 } )
genres_1
Because genres contains an array value, MongoDB stores this index as a multikey index.
Results
The index contains a key for each individual value that appears in the genres field. For example, for the movie The Godfather, which stores the genres Crime and Drama, the index contains one key for each genre. The index is ascending, meaning the keys are stored in ascending order.
The index supports queries that select on the genres field. For example, the following query returns movies where at least one element in the genres array is Short and the movie was released before 1910:
db.movies.find( { genres: "Short", year: { $lt: 1910 } }, { _id: 0, title: 1, year: 1, genres: 1 } )
[ { genres: [ 'Short', 'Western' ], title: 'The Great Train Robbery', year: 1903 }, { genres: [ 'Short', 'Drama' ], title: 'A Corner in Wheat', year: 1909 }, { genres: [ 'Short', 'Romance' ], title: 'The Kiss', year: 1896 }, { genres: [ 'Short', 'Romance' ], title: 'The Kiss', year: 1896 } ]
Note
Documents in the movies collection contain additional fields not shown here.
Learn More
To learn how to create a multikey index on embedded document fields, see Create an Index on an Embedded Field in an Array.
To learn about multikey index bounds, see Multikey Index Bounds.