This version will reach end of life on Feb 2018. To upgrade, go to the Learn more about upgrading your version of MongoDB.

Create a Unique Index

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.

MongoDB cannot create a unique index on the specified index field(s) if the collection already contains data that would violate the unique constraint for the index.

Unique Index on a Single Field

To create a unique index, consider the following prototype:

db.collection.createIndex( { a: 1 }, { unique: true } )

For example, you may want to create a unique index on the "tax-id" field of the accounts collection to prevent storing multiple account records for the same legal entity:

db.accounts.createIndex( { "tax-id": 1 }, { unique: true } )

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.

Unique Compound Index

You can also enforce a unique constraint on compound indexes, as in the following prototype:

db.collection.createIndex( { a: 1, b: 1 }, { unique: true } )

These indexes enforce uniqueness for the combination of index keys and not for either key individually.

Unique Index and Missing 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.

db.collection.createIndex( { a: 1 }, { unique: true, sparse: true } )

Refer to the createIndex() documentation for additional index creation options.