- Indexes >
- Indexing Tutorials >
- Index Creation Tutorials >
- Create a Unique Index
Create a Unique Index¶
On this page
MongoDB allows you to specify a unique constraint on an index. These constraints prevent applications from inserting documents that have duplicate values for the inserted fields. Additionally, if you want to create an index on a collection that has existing data that might have duplicate values for the indexed field, you may choose to combine unique enforcement with duplicate dropping.
Unique Indexes¶
To create a unique index, consider the following prototype:
For example, you may want to create a unique index on the "tax-id":
of the accounts
collection to prevent storing multiple account
records for the same legal entity:
The _id index is a unique index. In some
situations you may consider using the _id
field itself for this kind
of data rather than using a unique index on another field.
If a
document does not have a value for a field, the index entry for that
item will be null
in any index that includes it.
Thus, in many situations you will want to combine the unique
constraint
with the sparse
option. Sparse
indexes skip over any
document that is missing the indexed field, rather than storing
null
for the index entry. Since unique indexes
cannot have duplicate
values for a field, without the sparse
option, MongoDB will reject
the second document and all subsequent documents without the indexed
field. Consider the following prototype.
You can also enforce a unique constraint on compound indexes, as in the following prototype:
These indexes enforce uniqueness for the combination of index keys and not for either key individually.
Drop Duplicates¶
Deprecated since version 2.6: The dropDups
option to ensureIndex()
,
createIndex()
, and createIndexes
is deprecated.
To force the creation of a unique index
index on a collection with duplicate values in the field you are
indexing you can use the dropDups
option. This will force MongoDB
to create a unique index by deleting documents with duplicate values
when building the index. Consider the following prototype invocation
of ensureIndex()
:
See the full documentation of duplicate dropping for more information.
Warning
Specifying { dropDups: true }
may delete data from your
database. Use with extreme caution.
Refer to the ensureIndex()
documentation for additional index creation options.