Docs Menu
Docs Home
/ / /
PyMongo
/ /

Unique Indexes

On this page

  • Overview
  • Sample Data
  • Create a Unique Index
  • Collation
  • 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.

When you create an index, you can specify a default collation for all operations you perform on fields that are included in the index.

A collation is a set of language-specific rules for string comparison, such as for letter case and accent marks.

To specify a collation, create an instance of the Collation class or a Python dictionary. For a list of options to pass to the Collation constructor or include as keys in the dictionary, see Collation in the MongoDB Server manual.

Tip

Import Collation

To create an instance of the Collation class, you must import it from pymongo.collation.

To use an index with a specified collation, your operation must meet the following criteria:

  • The operation uses the same collation as the one specified in the index.

  • The operation is covered by the index that contains the collation.

The following example creates the same index as the previous example, but with a default collation of fr_CA:

theaters.create_index("theaterId", unique=True, collation=Collation(locale='fr_CA'))

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

Back

Geospatial