Wildcard Indexes (original) (raw)

MongoDB supports creating indexes on a field, or set of fields, to improve performance for queries. MongoDB supports flexible schemas, meaning document field names may differ within a collection. Use wildcard indexes to support queries against arbitrary or unknown fields.

To create a wildcard index, use the wildcard specifier ($**) as the index key:


db.collection.createIndex( { "$**": <sortOrder> } )

You can use the following commands to create a wildcard index:

Only use wildcard indexes when the fields you want to index are unknown or may change. Wildcard indexes don't perform as well as targeted indexes on specific fields. If your collection contains arbitrary field names that prevent targeted indexes, consider remodeling your schema to have consistent field names. To learn more about targeted indexes, seeCreate Indexes to Support Your Queries.

Consider using a wildcard index in the following scenarios:

You can perform the following tasks with wildcard indexes:

Wildcard indexes behave as follows:

Wildcard indexes can support a covered queryonly if all of the following conditions are true:

Consider the following wildcard index on the employees collection:


db.employees.createIndex( { "$**" : 1 } )

The following operation queries for a single field lastName and projects out all other fields from the resulting document:


db.employees.find(

  { "lastName" : "Doe" },

  { "_id" : 0, "lastName" : 1 }

)

If the specified lastName is never an array, MongoDB can use the$** wildcard index to support a covered query.

To learn more about wildcard indexes, see: