您可以对 复合索引实施唯一约束。唯一复合索引强制索引键值组合的唯一性。
要在MongoDB Shell中创建唯一索引,请使用db.collection.createIndex() 方法,并将unique 选项设立为true 。
db.collection.createIndex( { <field1>: <sortOrder>, <field2>: <sortOrder>, ... <fieldN>: <sortOrder> }, { unique: true } )
关于此任务
此示例在 members集合的 groupNumber、lastname 和 firstname 字段上添加唯一复合索引。该索引可确保这些字段值的组合对于集合中的每个文档都是唯一的。
步骤
要在 集合的 、 和groupNumberlastname firstnamemembersmongosh字段上创建唯一索引,运行以下命令:
db.members.createIndex( { groupNumber: 1, lastname: 1, firstname: 1 }, { unique: true } )
创建的索引强制 groupNumber、lastname 和 firstname 值的组合具备唯一性。
具有嵌入式数组的字段上的复合唯一索引
考虑包含以下文档的集合:
db.myColl.insertOne( { _id: 1, a: [ { loc: "A", qty: 5 }, { qty: 10 } ] } )
在 a.loc 和 a.qty 上创建唯一的复合多键索引:
db.myColl.createIndex( { "a.loc": 1, "a.qty": 1 }, { unique: true } )
唯一索引允许将以下文档插入集合,因为该索引强制 a.loc 和 a.qty 值的组合有唯一性:
db.myColl.insertMany( [ { _id: 2, a: [ { loc: "A" }, { qty: 5 } ] }, { _id: 3, a: [ { loc: "A", qty: 10 } ] } ] )