0
0
MongoDBquery~5 mins

Multikey indexes for arrays in MongoDB

Choose your learning style9 modes available
Introduction

Multikey indexes help you quickly find documents when you have arrays inside them. They make searching inside arrays fast and easy.

You have a list of tags for blog posts and want to find posts by tag quickly.
You store multiple phone numbers for each contact and want to search by any number.
You keep an array of product categories and want to find all products in a category.
You want to speed up queries that check if an array contains a specific value.
Syntax
MongoDB
db.collection.createIndex({ 'arrayField': 1 })

This creates a multikey index if 'arrayField' is an array in your documents.

The index works on each element inside the array separately.

Examples
Creates a multikey index on the 'tags' array field in the 'books' collection.
MongoDB
db.books.createIndex({ tags: 1 })
Indexes the 'phoneNumbers' array so you can quickly find contacts by any phone number.
MongoDB
db.contacts.createIndex({ phoneNumbers: 1 })
Indexes the 'categories' array to speed up category searches.
MongoDB
db.products.createIndex({ categories: 1 })
Sample Program

This example creates a collection 'books' with a 'tags' array. It adds a multikey index on 'tags' to speed up searches. Then it finds all books tagged 'fiction' and prints their titles.

MongoDB
use myLibrary

// Insert sample documents with arrays
db.books.insertMany([
  { title: 'Book A', tags: ['fiction', 'adventure'] },
  { title: 'Book B', tags: ['non-fiction', 'history'] },
  { title: 'Book C', tags: ['fiction', 'mystery'] }
])

// Create a multikey index on the tags array
db.books.createIndex({ tags: 1 })

// Query to find books with tag 'fiction'
const fictionBooks = db.books.find({ tags: 'fiction' }).toArray()

// Print the titles of books found
fictionBooks.forEach(book => print(book.title))
OutputSuccess
Important Notes

Multikey indexes automatically handle arrays without extra setup.

They can slow down writes because the index updates for each array element.

Use multikey indexes when you often search for values inside arrays.

Summary

Multikey indexes speed up queries on array fields by indexing each element.

They are easy to create by indexing the array field normally.

Great for searching tags, categories, or any list inside documents.