Skip to content

Indexing

Multikey Indexes

Indexing array values, and the limits that come with them.

IntermediateAbout 5 minutes

Index an array field and MongoDB stores one key per element. That is a multikey index. { skills: "MongoDB" } can seek. The cost is size: ten skills → ten keys. An unbounded array (events on the user) makes an unbounded index.

db.users.createIndex({ skills: 1 })
db.users.find({ skills: "MongoDB" })

db.orders.createIndex({ "items.name": 1 })
db.orders.find({ "items.name": "Mechanical Keyboard" })
Rahul's skills. Nested array path is also multikey.

A compound index may include at most one array field. { tags: 1, scores: 1 } if both are arrays — cannot build. { userId: 1, "items.name": 1 } is allowed (userId is scalar). Multikey plus a sort on another field is easy to get wrong; prove it with explain() next module. $elemMatch can use a multikey index; it does not need a special index type.

Interview question

What is a multikey index, and what is the compound-index restriction?

Think about it first.