## Enforce Unique Keys for Sharded Collections 

## Overview 

The unique constraint on indexes ensures that only one document can have a value for a field in a collection . For sharded collections these unique indexes cannot enforce uniqueness because insert and indexing operations are local to each shard. 

MongoDB does not support creating new unique indexes in sharded collections and will not allow you to shard col- lections with unique indexes on fields other than the _id field. 

If you need to ensure that a field is always unique in a sharded collection, there are three options: 

1. Enforce uniqueness of the shard key (page 674). 

MongoDB can enforce uniqueness for the shard key . For compound shard keys, MongoDB will enforce unique- ness on the entire key combination, and not for a specific component of the shard key. 

You cannot specify a unique constraint on a hashed index (page 502). 

2. Use a secondary collection to enforce uniqueness. 

Create a minimal collection that only contains the unique field and a reference to a document in the main collection. If you always insert into a secondary collection before inserting to the main collection, MongoDB will produce an error if you attempt to use a duplicate key. 

If you have a small data set, you may not need to shard this collection and you can create multiple unique indexes. Otherwise you can shard on a single unique key. 

3. Use guaranteed unique identifiers. 

Universally unique identifiers (i.e. UUID) like the ObjectId are guaranteed to be unique. 

## Procedures 

## Unique Constraints on the Shard Key 

Process To shard a collection using the unique constraint, specify the shardCollection command in the following form: 

db.runCommand( { shardCollection : "test.users" , key : { email : 1 } , unique : true } ); 

Remember that the _id field index is always unique. By default, MongoDB inserts an ObjectId into the _id field. However, you can manually insert your own value into the _id field and use this as the shard key. To use the _id field as the shard key, use the following operation: 

db.runCommand( { shardCollection : "test.users" } ) 

## Limitations 

• You can only enforce uniqueness on one single field in the collection using this method. 

• If you use a compound shard key, you can only enforce uniqueness on the combination of component keys in the shard key. 

In most cases, the best shard keys are compound keys that include elements that permit write scaling (page 675) and query isolation (page 676), as well as high cardinality (page 696). These ideal shard keys are not often the same keys that require uniqueness and enforcing unique values in these collections requires a different approach. 

