Search code examples
mongodbindexingshardingmongodb-indexes

In Mongo, are unique indexes supported for sharded environments?


We're exploring Mongo for a new website and we want to ensure no two users sign up with the same email address, so, a unique index on the email field is necessary.

Is this supported in a sharded Mongo environment? Mongo documentation states unique indexes are supported, but makes no mention of shards.

http://www.mongodb.org/display/DOCS/Indexes#Indexes-UniqueIndexes


Solution

  • From the documentation:

    You can use the {unique: true} option to ensure that the underlying index enforces uniqueness so long as the unique index is a prefix of the shard key. (note: prior to version 2.0 this worked only if the collection is empty).

    http://www.mongodb.org/display/DOCS/Configuring+Sharding

    This makes intuitive sense, as mongodb has no way of checking uniqueness across shards, unless the shard key gives you such cross-shard uniqueness guarantees "for free".