Video Transcript (English)
Hi! In this video, we’ll define multikey indexes and discuss how MongoDB works with array fields that are used in indexes.
We’ll also work with a multikey single field index.
Let’s work through an example by using the customers collection.
This collection contains details about each customer. It includes the email as a unique string to identify each customer, the customer’s birthdate date, and the accounts related to the customer in an array field.
In a collection, there are different field types, including arrays and subdocuments. For example, the documents in the customers collection includes the "accounts" field which is an array.
When we define an index on an array field, that index is called a multikey index.
Multikey indexes can index primitives, subdocuments, or subarrays.
We can have an array field in a single field index or in a compound index.
For instance, these two commands will create multikey indexes, because they include the field accounts, which is an array.
There is a limitation of only one array field per index. So, if an index has multiple fields, only one of them can be an array.
Internally, MongoDB decomposes the array and stores each unique value found within it as an individual index entry.
If we have an application that runs queries on the accounts collection, and we wanted to find customers with a specific account number, we should also have an index on the accounts field.
When we use the getIndexes() method to find the indexes in the collection, the output indicates that there are three indexes: the default index on _id, and two more single-field indexes on the birthdate and email fields.
This shows no index on the accounts field. Let’s confirm that another way.
We can run the explain command to see the query execution plan.
Explain will show us that our query currently searches for documents with the account 627788…. And that our query forces the database to perform a collection scan because there is no index on the accounts array.
Let’s fix that.
We can create a single field index on the accounts field for the customers collection.
Excellent! The accounts_1 index is now created as a single field multikey index.
Now we’ll repeat the previous explain command to see the execution plan for the query that searches for customers with the 627788 account.
Great! The output shows that MongoDB uses the new index in the IXSCAN stage. The index is on the accounts field that is a multikey index.
Note that multikey indexes need to fetch the documents after the IXSCAN stage, because the index entries have each of the array values stored separately.
Congratulations! Now you know how to index arrays by using multikey indexes in MongoDB. Let’s recap what you learned in this video:
A multikey index is any index where one of the indexed fields contains an array.
The array can hold nested objects or other field types.
In a compound index, only one of the fields can be an array.
