Single Field Indexes
On this page
Overview
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.
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 Single Field Index
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.