MongoDB Multikey Indexes Examples
In the following example, we are working with:
Database: gfg
Collections: student
Document: Three documents contains the details of the students
Example 1: Creating a multikey index
Now we create multi-index with the help of createIndex() method on the field language:
Query:
db.student.createIndex({language:1})
After indexing, we will check the index using the getIndexes() method:
Example 2: Indexing an array with the embedded document
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:
- When you are creating a compound multikey index then each indexed document must contain at most one indexed field whose value is an array.
- You are not allowed to create a compound multikey index if more than one to be indexed field of a document is an array.
- When the compound multikey index already exists, then you are not allowed to insert a document that will break the restrictions.
- When a field is an array of documents, you are allowed to index an embedded document to create a compound index but at most one indexed field can be an array.
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 indexing 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.
Contact Us