Docs Menu

Docs HomeDevelop ApplicationsPython DriversPyMongo

Clustered Indexes

On this page

  • Overview
  • Sample Data
  • Create a Clustered Index

Clustered indexes instruct a collection to store documents ordered by a key value. To create a clustered index, perform the following steps when you create your collection:

  • Specify the clustered index option with the _id field as the key.

  • Set the unique field to True.

The examples in this guide use the sample_mflix database 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 clustered index on the _id field in a new movie_reviews collection:

sample_mflix.create_collection("movies", clusteredIndex={
"key": { "_id": 1 },
"unique": True
})

For more information, see the Clustered Index and Clustered Collections sections in the MongoDB Server manual.

← Wildcard Indexes