liveBook · Manning

Multikey index

As explained in MongoDB 8.0 in Action, Third Edition

A multikey index is a MongoDB index that creates index entries for the elements of an array field to support efficient queries on array contents.

A multikey index is a MongoDB B-tree index for array values. MongoDB creates separate index entries for each array element, allowing efficient queries that test for specific values or criteria. Arrays may contain scalar values or embedded documents; repeated occurrences of the same value produce one index entry. section 7.2.3

Listing 7.8 Multikey index prototype
db.<collection>.createIndex( { <arrayField>: <sortOrder> } )

Use the index prototype by replacing the collection name, array field, and sort order with application-specific values. section 7.2.3

A practical customer-account workflow is:

  • Create an index for the accounts array: db.customers.createIndex({ accounts: 1 }). section 7.2.3
  • Query customers by an account number: db.customers.find({ accounts: 371138 }). section 7.2.3
  • For frequent username-and-account queries, create { username: 1, accounts: 1 }; the scalar username field may accompany the array field. section 7.2.3
  • Query both fields with db.customers.find({ username: 'fmiller', accounts: 371138 }). section 7.2.3

Embedded-document array

For an array of embedded documents, index the nested score field with db.grades.createIndex({ "scores.score": 1 }). Then query scores above 70 with db.grades.find({ "scores.score": { $gt: 70 } }) or sort by that field with db.grades.find().sort({ "scores.score": -1 }). section 7.2.3

A compound multikey index can include only one array field, preventing an overly complex index structure. Hashed indexes cannot support array fields, so a hashed index cannot replace a multikey index for array queries. section 7.2.3 section 7.2.7

Inspect query efficiency with db.collection.explain() or cursor.explain(), using queryPlanner, executionStats, or allPlansExecution verbosity levels when diagnosing index use and response costs. section 7.8

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Explains array-entry creation, duplicate-value handling, compound-field limits, nested fields, and practical commands.
Examples
Uses customer account arrays, username-account lookups, and grades containing embedded score documents.
What you can do after
Apply it via mongosh by creating array-field indexes and diagnosing their query plans with explain().
How it connects
Connects array fields with compound indexes, embedded documents, hashed indexes, and query planners.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.