Docs 菜单
Docs 主页
/ /

具有唯一索引的分片集合

分分片的集合不支持唯一索引,除非该索引是分片键或将其作为前缀。

索引上的唯一性约束可确保集合中的文档在字段上设立唯一值。对于分片的集合, MongoDB不会对字段实施唯一性约束,除非索引是分片键或其包含分片键作为前缀。要防止出现问题,请执行以下操作:

1

创建索引用作分片键的索引:

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

为集合创建唯一索引。将分片键作为索引的前缀包含在内:

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

后退

转换为唯一