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
