Open In App

MongoDB – Multikey Indexes

Indexes are special data structures that store some information related to the documents such that it becomes easy for MongoDB to find the right data file. They also store the value of a specific field or set of fields, ordered by the value of the field as specified in the index. MongoDB allows to index a field that holds an array value by creating an index key for each element in the array, such type of indexing is called Multikey indexes. It supports efficient queries against array fields. It can be constructed over arrays that hold both scalar values(like strings, numbers, etc) and nested documents.

How to Create Multikey Index?

In MongoDB, we can create Multikey indexes using the createIndex() method



Syntax:

db.Collection_name.createIndex({filed_name: 1/ -1})



Important Points:

Examples:

In the following example, we are working with:

Database: gfg

Collections: student

Document: Three documents contains the details of the students

Now we create multi-index with the help of createIndex() method on the field language:

db.student.createIndex({language:1})

After indexing, we will check the index using the getIndexes() method:

You are allowed to create a multikey index on an array field that contains nested documents/objects.

db.student.createIndex({"details.age":1, "details.branch":1})

Here, we create the multikey index on the “details.age” and “details.branch” fields.

After indexing, we will check the index using the getIndexes() method:

Limitations:

Article Tags :