Docs Menu
Docs Home
/ / /
PyMongo
/ /

Single Field Indexes

On this page

  • Overview
  • Sample Data
  • Create Single Field Index
  • Collation

Single field indexes are indexes with a reference to a single field within a collection's documents. They improve single field query and sort performance, and support TTL Indexes that automatically remove documents from a collection after a certain amount of time or at a specific clock time.

Note

The _id_ index is an example of a single field index. This index is automatically created on the _id field when a new collection is created.

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.

The following example creates an index in ascending order on the title field:

movies.create_index("title")

The following is an example of a query that is covered by the index created in the preceding code example:

query = { "title": "Batman" }
sort = [("title", 1)]
cursor = movies.find(query).sort(sort)

To learn more, see Single Field Indexes in the MongoDB Server manual.

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:

from pymongo.collation import Collation
movies.create_index("title", collation=Collation(locale='fr_CA'))

Back

Work with Indexes