What is Multikey Index in MongoDB: Explanation and Example
multikey index in MongoDB is an index type that allows indexing fields that hold arrays. It creates separate index entries for each element in the array, enabling efficient queries on array values.How It Works
Imagine you have a list of tags for each blog post, like ['mongodb', 'database', 'index']. A multikey index treats each tag as a separate item to index. Instead of indexing the whole array as one value, it indexes each element individually.
This means when you search for posts tagged with 'database', MongoDB can quickly find all posts containing that tag without scanning every document. It works like having multiple index entries per document, one for each array element.
Under the hood, MongoDB creates multiple index keys for each array element, making queries on array fields fast and efficient.
Example
This example shows how to create a multikey index on an array field and query it.
use mydb;
db.posts.insertMany([
{ title: "Post 1", tags: ["mongodb", "database"] },
{ title: "Post 2", tags: ["index", "performance"] },
{ title: "Post 3", tags: ["mongodb", "index"] }
]);
db.posts.createIndex({ tags: 1 });
db.posts.find({ tags: "mongodb" });When to Use
Use a multikey index when you have fields that store arrays and you want to efficiently search for documents containing specific array elements. For example:
- Tagging systems where items have multiple tags.
- Storing lists of categories, keywords, or labels.
- Searching user interests or skills stored as arrays.
This index improves query speed on array fields but can increase index size, so use it when array queries are common.
Key Points
- A multikey index indexes each element of an array separately.
- It enables fast queries on array fields.
- Automatically created when you index an array field.
- Can increase index size due to multiple entries per document.