Unique Indexes

Unique Indexes

数组字段的唯一性约束唯一约束适用于集合中的独立文档。换言之,唯一索引可以防止独立文档为该索引键具有相同的值。

由于该约束适用于独立文档,因此对于唯一多键索引,只要某文档的索引键值与其他文档的索引键值不重复,该文档就可能包含导致重复索引键值的数组元素。在这种情况下,重复的索引条目仅插入索引一次。

示例,考虑一个 inventory集合,其中包含以下表示产品及其股票位置的文档:

db.inventory.insertMany( [ { _id: 1, product: "pencils", inventory: [ { warehouse: "NYC", quantity: 5 }, { quantity: 10 } ] }, { _id: 2, product: "pens", inventory: [ { warehouse: "NYC" }, { quantity: 5 } ] }, { _id: 3, product: "markers", inventory: [ { warehouse: "NYC", quantity: 10 } ] }] )在 inventory.warehouse 和 inventory.quantity 上创建唯一复合多键索引:

db.products.createIndex( { "inventory.warehouse": 1, "inventory.quantity": 1 }, { unique: true } )如果此集合中没有其他文档的索引键值为 { "inventory.warehouse": "LA", "inventory.quantity": null },则该唯一索引允许将以下文档插入集合:

db.products.insertOne( { _id: 4, product: "Sprocket", inventory: [ { warehouse: "LA" }, { warehouse: "LA" } ] } )

相关推荐