Docs Home / Indexes / Properties / Unique

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.除非索引是分片键或将其作为前缀包含在内,否则分片集合不支持唯一索引。

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:索引的唯一性约束确保集合中的文档在字段上设置了唯一的值。对于分片集合,MongoDB不会对字段强制执行唯一性约束,除非索引是分片键或包含分片键作为前缀。为防止出现问题:

  • On a sharded colelction, if you create a unique index that doesn't use the shard key, MongoDB returns an error to the createIndexes command.在分片集合中,如果你创建了一个不使用分片键的唯一索引,MongoDB会向createIndexes命令返回错误。
  • 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 shardCollection command.如果你对一个集合进行分片,并且该集合包含一个不使用分片键的唯一索引,MongoDB会向shardCollection命令返回错误。

Steps步骤

1

Create the shard key创建分片键

Create the index you plan to use as the shard key:创建您计划用作分片键的索引:

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

Create a unique index创建唯一索引

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

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

Learn More了解更多