For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

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:

  • For sharded collections, if you create a unique index that doesn't use the shard key, MongoDB returns an error when you run the createIndexes command.

  • If you shard a collection and the collection contains a unique index that doesn't use the shard key, MongoDB returns an error when you run the shardCollection command.

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 } )
}