Docs Menu

Docs HomeDevelop ApplicationsPython DriversPyMongo

Compound Indexes

On this page

  • Overview
  • Sample Data
  • Create a Compound Index

Compound indexes hold references to multiple fields within a collection's documents, improving query and sort performance.

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 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.

← Single-Field Indexes