Docs Menu

Docs HomeDevelop ApplicationsPython DriversPyMongo

Unique Indexes

On this page

  • Overview
  • Sample Data
  • Create a Unique Index
  • Troubleshooting
  • DuplicateKeyException

Unique indexes ensure that the indexed fields do not store duplicate values. By default, MongoDB creates a unique index on the _id field during the creation of a collection. To create a unique index, perform the following steps:

  • Specify the field or combination of fields that you want to prevent duplication on.

  • Set the unique option to``True``.

The examples in this guide use the sample_mflix.theaters 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 descending unique index on the theaterId field:

theaters.create_index("theaterId", unique=True)

For more information, see the Unique Indexes guide in the MongoDB Server manual.

If you perform a write operation that stores a duplicate value that violates a unique index, the driver raises a DuplicateKeyException, and MongoDB throws an error resembling the following:

E11000 duplicate key error index
← Geospatial Indexes