Docs Menu
Docs Home
/ /

Sharded Collections with Unique Indexes

Unique indexes are not supported on sharded collections unless the index is the shard key or includes it as a prefix.

The uniqueness constraint on an index ensures that documents in the collection have a unique value set on the field. With sharded collections, MongoDB does not enforce the uniqueness constraint on the field unless the index is the shard key or it includes the shard key as a prefix. To prevent issues:

1

Create the index you plan to use as the shard key:

db.names.createIndex( { region_id: 1 } )
region_id_1
2

Create the unique index for the collection. Include the shard key as a prefix for the index:

db.names.createIndex(
{ region_id: 1, email: 1 },
{ unique: true }
)
region_id_1_email_1
3
sh.shardCollection( "accounts.names", { region_id: 1 } )
{
collectionsharded: 'accounts.names',
ok: 1,
'$clusterTime': {
clusterTime: Timestamp( { t: 1759260515, i: 58 } ),
signature: {
hash: Binary.createFromBase64( 'AAAAAAAAAAAAAAAAAAAAAAAAAAA=', 0 ),
keyId: Long( '0' )
}
},
operationTime: Timestamp( { t: 1759260515, i: 57 } )
}

Back

Convert to Unique