Docs Home / Indexes / Properties / Unique

Create a Compound Unique Index创建复合唯一索引

You enforce a unique constraint on compound indexes. A unique compound index enforces uniqueness on the combination of the index key values.您对a href="/v8.3/core/indexes/index-types/index-compound/#std-label-index-type-compound">复合索引实施了唯一的约束。唯一复合索引强制索引键值组合的唯一性。

To create a unique index in the MongoDB Shell, use the db.collection.createIndex() method with the unique option set to true.要在MongoDB Shell中创建唯一索引,请使用db.collection.createIndex()方法,并将unique选项设置为true

db.collection.createIndex(
{
<field1>: <sortOrder>,
<field2>: <sortOrder>,
...
<fieldN>: <sortOrder>
},
{ unique: true }
)

About this Task关于此任务

This example adds a unique compound index on the groupNumber, lastname, and firstname fields of a members collection. The index ensures that the combination of these field values is unique for each document in the collection.此示例在成员集合的groupNumberlastnamefirstname字段上添加了一个唯一的复合索引。索引确保这些字段值的组合对于集合中的每个文档都是唯一的。

Steps步骤

To create a unique index on groupNumber, lastname, and firstname fields of the members collection, run the following command in mongosh:要在成员集合的groupNumberlastnamefirstname字段上创建唯一索引,请在mongosh中运行以下命令:

db.members.createIndex(
{ groupNumber: 1, lastname: 1, firstname: 1 },
{ unique: true }
)

The created index enforces uniqueness for the combination of groupNumber, lastname, and firstname values.创建的索引强制groupNumberlastnamefirstname值的组合具有唯一性。

Compound Unique Indexes on Fields with Embedded Arrays具有嵌入式数组的字段上的复合唯一索引

Consider a collection with the following document:考虑一个包含以下文档的集合:

db.myColl.insertOne(
{ _id: 1, a: [ { loc: "A", qty: 5 }, { qty: 10 } ] }
)

Create a unique compound multikey index on a.loc and a.qty:a.loca.qty上创建一个唯一的复合多键索引:

db.myColl.createIndex( { "a.loc": 1, "a.qty": 1 }, { unique: true } )

The unique index permits the insertion of the following documents into the collection since the index enforces uniqueness for the combination of a.loc and a.qty values:唯一索引允许将以下文档插入到集合中,因为该索引强制执行a.loca.qty值组合的唯一性:

db.myColl.insertMany( [
{ _id: 2, a: [ { loc: "A" }, { qty: 5 } ] },
{ _id: 3, a: [ { loc: "A", qty: 10 } ] }
] )

Learn More了解更多