Unique indexes are not supported on sharded collections unless the index is the shard key or includes it as a prefix.
About this Task
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:
On a sharded colelction, if you create a unique index that doesn't use the shard key, MongoDB returns an error to the
createIndexescommand.If you shard a collection and the collection contains a unique index that doesn't use the shard key, MongoDB returns an error to the
shardCollectioncommand.
Steps
1
2
3
Shard the collection
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 } ) }