Wildcard Indexes
Overview
Wildcard indexes enable queries against unknown or arbitrary fields. These indexes can be beneficial if you are using a dynamic schema.
Sample Data
The examples in this guide use the sample_mflix.movies
collection
from the Atlas sample datasets. To learn how to create a
free MongoDB Atlas cluster and load the sample datasets, see the
Get Started with PyMongo.
Create a Wildcard Index
The following example creates an ascending wildcard index on all
values of the location
field, including values nested in subdocuments and arrays:
movies.create_index({ "location.$**": pymongo.ASCENDING })
For more information, see the Wildcard Indexes page in the MongoDB Server manual.
Collation
When you create an index, you can specify a default collation for all operations you perform on fields that are included in the index.
A collation is a set of language-specific rules for string comparison, such as for letter case and accent marks.
To specify a collation, create an instance of the Collation
class or a Python dictionary.
For a list of options to pass to the Collation
constructor or include as keys in the
dictionary, see Collation in the MongoDB Server manual.
Tip
Import Collation
To create an instance of the Collation
class, you must import it from
pymongo.collation
.
To use an index with a specified collation, your operation must meet the following criteria:
The operation uses the same collation as the one specified in the index.
The operation is covered by the index that contains the collation.
The following example creates the same index as the previous example,
but with a default collation of fr_CA
:
movies.create_index({ "location.$**": pymongo.ASCENDING }, collation=Collation(locale='fr_CA'))