Docs Menu
Docs Home
/ / /
PyMongo
/ /

Single-Field Indexes

On this page

  • Overview
  • Sample Data
  • Create Single-Field Index

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.

Back

Work with Indexes