Compound Indexes
On this page
Overview
Compound indexes hold references to multiple fields within a collection's documents, improving query and sort performance.
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 Compound Index
The following example creates a compound index on the type
and genre
fields:
movies.create_index([("type", pymongo.ASCENDING), ("genre", pymongo.ASCENDING)])
The following is an example of a query that uses the index created in the preceding code example:
query = { "type": "movie", "genre": "Drama" } sort = [("type", pymongo.ASCENDING), ("genre", pymongo.ASCENDING)] cursor = movies.find(query).sort(sort)
For more information, see Compound Indexes in the MongoDB Server manual.