0
0
MongodbConceptBeginner · 3 min read

What is Multikey Index in MongoDB: Explanation and Example

A 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.

mongodb
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" });
Output
[ { "_id": ObjectId("..."), "title": "Post 1", "tags": ["mongodb", "database"] }, { "_id": ObjectId("..."), "title": "Post 3", "tags": ["mongodb", "index"] } ]
🎯

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.

Key Takeaways

A multikey index indexes each element in an array field separately for fast queries.
It is useful when querying documents by values inside array fields.
MongoDB automatically creates multikey indexes when indexing array fields.
Multikey indexes can increase index size due to multiple entries per document.
Use multikey indexes to improve performance on array value searches.