Multikey Indexes in MongoDB

In this article, we will see how Multikey indexes works in MongoDB.This type of index is used when one of the keys in index is of type array. It will allow queries to be select documents containing array elements by matching elements in them. User don’t have to explicitly mention that particular index is Multikey index as Mongo will implicitly identifies whether to create Multikey index or not based on keys passed for index creation.

In order to understand Multikey indexes, lets consider the employee collection as shown below

Now if you try to create compound index on employee_id and hobbies keys then mongo will internally use index values as, employee_id with each value in hobbies array. Index will look as shown

123,’hiking’
123,’cycling’
123,’golf’

In this example we cannot create compound index on (roles, hobbies), as it is not supported since it will lead to cartesian product of arrays in this case.

Following are different combination for creating Multikey index
  • Index with combinations of multiple scalar keys is valid
  • Index with combination of multiple scalar keys and one Array is valid
  • Index with combination of Multiple Array keys is invalid

    Dot Notation in Multikey Indexes

    The Dot notation is generally used to index elements, which are deep in document.In our example if we want to create index on name element in dept array then we can use Dot notation as shown below

    This is all about Multikey index in MongoDB.

    Happy Learning!!!

Leave a Reply

Your email address will not be published. Required fields are marked *