Multikey and wildcard indexes
Index arrays and fields you do not know beforehand.
Index the values of an array with a multikey index, or every field of an embedded document with a wildcard index.
Requirements
- A user with
dbAdminorreadWriteon the database.
Index an array
An index on a field that is an array has one entry per element; you do not have to ask for it:
JavaScript
db.products.createIndex({ tags: 1 });Index unknown fields
JavaScript
db.products.createIndex({ "attributes.$**": 1 });Check
The explain of db.products.find({ tags: "eco" }) shows that the query uses the tags_1 index instead of scanning
the collection.
Common problems
- A wildcard index cannot be unique. If you try to make it unique with
collMod, it answers error 67.