Indexing
Multikey Indexes
Indexing array values, and the limits that come with them.
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" })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?
An index on an array stores one entry per element so queries can match a value in the array. A compound index can include at most one array field. Large arrays multiply index size — another reason unbounded arrays are a modeling bug.