唯一索引
在本页面
新的内部格式从MongoDB 4.2开始,对于4.2(或更高版本)的featureCompatibilityVersion(fCV),MongoDB使用一种新的内部格式来存储与早期MongoDB版本不兼容的唯一索引。新格式适用于现有的唯一索引以及新创建/重建的唯一索引。
db.collection.createIndex( <key and index type specification>, { unique: true } )
db.members.createIndex( { "user_id": 1 }, { unique: true } )
db.members.createIndex( { groupNumber: 1, lastname: 1, firstname: 1 }, { unique: true } )
创建的索引强制
groupNumber
、lastname
和firstname
值的_组合_的唯一性。再举一个例子,考虑一个包含以下文档的集合:
{ _id: 1, a: [ { loc: "A", qty: 5 }, { qty: 10 } ] }
db.collection.createIndex( { "a.loc": 1, "a.qty": 1 }, { unique: true } )
唯一索引允许将以下文档插入到集合中,因为索引强制
a.loc
和a.qty
值组合的唯一性:db.collection.insert( { _id: 2, a: [ { loc: "A" }, { qty: 5 } ] } )
db.collection.insert( { _id: 3, a: [ { loc: "A", qty: 10 } ] } )
也可以看看:
唯一约束适用于集合中的不同文档。也就是说,唯一索引防止_单独的_文档对索引键具有相同的值。
例如,考虑一个包含以下文档的集合:
{ _id: 1, a: [ { loc: "A", qty: 5 }, { qty: 10 } ] }
{ _id: 2, a: [ { loc: "A" }, { qty: 5 } ] }
{ _id: 3, a: [ { loc: "A", qty: 10 } ] }
在
a.loc
和a.qty
上创建唯一的复合多键索引:db.collection.createIndex( { "a.loc": 1, "a.qty": 1 }, { unique: true } )
如果集合中的其他文档的索引 key value 为
{ "a.loc": "B", "a.qty": null }
,则唯一索引允许将以下文档插入到集合中。db.collection.insert( { _id: 4, a: [ { loc: "B" }, { loc: "B" } ] } )
如果文档在唯一索引中没有索引字段的值,索引将为该文档存储空值。由于唯一的约束,MongoDB将只允许一个没有索引字段的文档。如果有多个文档没有索引字段的值或缺少索引字段,索引构建将失败,并出现重复键错误。
例如,一个集合在
x
上有一个唯一的索引:db.collection.createIndex( { "x": 1 }, { unique: true } )
如果集合中没有包含缺少
x
字段的文档,唯一索引允许插入没有x
字段的文档:db.collection.insert( { y: 1 } )
但是,如果集合中已经包含了一个没有字段
x
的文档,则在插入一个没有字段x
的文档时出现唯一的索引错误:db.collection.insert( { z: 1 } )
由于违反了字段
x
值的唯一约束,操作无法插入文档:WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "E11000 duplicate key error index: test.collection.$a.b_1 dup key: { : null }"
}
})
也可以看看:
3.2版本新增.
唯一的索引约束意味着:
- 对于要分片的集合,如果该集合有其他唯一索引,则不能对该集合进行分片。
- 对于已经分片的集合,不能在其他字段上创建唯一索引。
最近更新 1yr ago