Unique Indexes唯一索引

On this page本页内容

A unique index ensures that the indexed fields do not store duplicate values; i.e. enforces uniqueness for the indexed fields. 唯一索引确保索引字段不存储重复值;亦即,强制索引字段的唯一性。By default, MongoDB creates a unique index on the _id field during the creation of a collection.默认情况下,MongoDB在创建集合期间在_id字段上创建唯一索引。

New Internal Format新的内部格式

Starting in MongoDB 4.2, for featureCompatibilityVersion (fCV) of 4.2 (or greater), MongoDB uses a new internal format for unique indexes that is incompatible with earlier MongoDB versions. 从MongoDB 4.2开始,对于4.2(或更高版本)的featureCompatibilityVersion(fCV),MongoDB为唯一索引使用了一种新的内部格式,该格式与早期的MongoDB版本不兼容。The new format applies to both existing unique indexes as well as newly created/rebuilt unique indexes.新格式既适用于现有的唯一索引,也适用于新创建/重建的唯一索引。

Create a Unique Index创建一个唯一的索引

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

db.collection.createIndex( <key and index type specification>, { unique: true } )

Unique Index on a Single Field单个字段上的唯一索引

For example, to create a unique index on the user_id field of the members collection, use the following operation in the mongo shell:例如,要在members集合的user_id字段上创建唯一索引,请在mongo shell中使用以下操作:

db.members.createIndex( { "user_id": 1 }, { unique: true } )

Unique Compound Index唯一复合索引

You can also enforce a unique constraint on compound indexes. 还可以对复合索引实施唯一约束。If you use the unique constraint on a compound index, then MongoDB will enforce uniqueness on the combination of the index key values.如果对复合索引使用唯一约束,那么MongoDB将对索引键值的组合强制唯一性。

For example, to create a unique index on groupNumber, lastname, and firstname fields of the members collection, use the following operation in the mongo shell:例如,要在members集合的groupNumberlastnamefirstname字段上创建唯一索引,请在mongo shell中使用以下操作:

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值的组合具有唯一性。

For another example, consider a collection with the following document:再举一个例子,考虑一个带有以下文档的集合:

{ _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.collection.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.collection.insert( { _id: 2, a: [ { loc: "A" }, { qty: 5 } ] } )
db.collection.insert( { _id: 3, a: [ { loc: "A", qty: 10 } ] } )

Behavior行为

Restrictions限制

MongoDB cannot create a unique index on the specified index field(s) if the collection already contains data that would violate the unique constraint for the index.如果集合已包含违反索引唯一约束的数据,MongoDB无法在指定的索引字段上创建唯一索引。

You may not specify a unique constraint on a hashed index.不能在散列索引上指定唯一约束。

Building Unique Index on Replica Sets and Sharded Clusters在副本集和分片集群上构建唯一索引

For replica sets and sharded clusters, using a rolling procedure to create a unique index requires that you stop all writes to the collection during the procedure. 对于副本集和分片集群,使用滚动过程创建唯一索引需要在该过程中停止对集合的所有写入。If you cannot stop all writes to the collection during the procedure, do not use the rolling procedure. 如果在此过程中无法停止对集合的所有写入,请不要使用滚动过程。Instead, build your unique index on the collection by:相反,可以通过以下方式在集合上建立唯一索引:

Unique Constraint Across Separate Documents跨单独文档的唯一约束

The unique constraint applies to separate documents in the collection. 唯一约束适用于集合中的单独文档。That is, the unique index prevents separate documents from having the same value for the indexed key.也就是说,唯一索引防止单独的文档对索引键具有相同的值。

Because the constraint applies to separate documents, for a unique multikey index, a document may have array elements that result in repeating index key values as long as the index key values for that document do not duplicate those of another document. 由于该约束适用于单独的文档,因此对于唯一的多键索引,只要该文档的索引键值不与另一个文档的索引键值重复,该文档可能具有导致重复索引键值的数组元素。In this case, the repeated index entry is inserted into the index only once.在这种情况下,重复的索引项只插入索引一次。

For example, consider a collection with the following documents:例如,考虑一个具有以下文档的集合:

{ _id: 1, a: [ { loc: "A", qty: 5 }, { qty: 10 } ] }
{ _id: 2, a: [ { loc: "A" }, { qty: 5 } ] }
{ _id: 3, a: [ { loc: "A", qty: 10 } ] }

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

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

The unique index permits the insertion of the following document into the collection if no other document in the collection has an index key value of { "a.loc": "B", "a.qty": null }.如果集合中没有其他文档的索引键值为{ "a.loc": "B", "a.qty": null },则唯一索引允许将以下文档插入集合。

db.collection.insert( { _id: 4, a: [ { loc: "B" }, { loc: "B" } ] } )

Unique Index and Missing Field唯一索引和缺失字段

If a document does not have a value for the indexed field in a unique index, the index will store a null value for this document. 如果文档在唯一索引中没有索引字段的值,索引将为此文档存储空值。Because of the unique constraint, MongoDB will only permit one document that lacks the indexed field. 由于唯一约束,MongoDB只允许一个缺少索引字段的文档。If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error.如果有多个文档没有索引字段的值或缺少索引字段,则索引生成将失败,并出现重复键错误。

For example, a collection has a unique index on x:例如,集合在x上有一个唯一的索引:

db.collection.createIndex( { "x": 1 }, { unique: true } )

The unique index allows the insertion of a document without the field x if the collection does not already contain a document missing the field x:如果集合中尚未包含缺少字段x的文档,则唯一索引允许插入不带字段x的文档:

db.collection.insert( { y: 1 } )

However, the unique index errors on the insertion of a document without the field x if the collection already contains a document missing the field x:但是,如果集合中已包含缺少字段x的文档,则插入不带字段x的文档时,唯一索引发生错误:

db.collection.insert( { z: 1 } )

The operation fails to insert the document because of the violation of the unique constraint on the value of the field x:由于违反了字段x值的唯一约束,操作无法插入文档:

WriteResult({
   "nInserted" : 0,
   "writeError" : {
      "code" : 11000,
      "errmsg" : "E11000 duplicate key error index: test.collection.$a.b_1 dup key: { : null }"
   }
})

Unique Partial Indexes唯一部分索引

New in version 3.2.版本3.2中的新功能。

Partial indexes only index the documents in a collection that meet a specified filter expression. 部分索引仅对集合中满足指定筛选表达式的文档进行索引。If you specify both the partialFilterExpression and a unique constraint, the unique constraint only applies to the documents that meet the filter expression.如果同时指定partialFilterExpression唯一约束,则唯一约束仅适用于满足筛选表达式的文档。

A partial index with a unique constraint does not prevent the insertion of documents that do not meet the unique constraint if the documents do not meet the filter criteria. 如果文档不符合筛选条件,则具有唯一约束的部分索引不会阻止插入不符合唯一约束的文档。For an example, see Partial Index with Unique Constraint.有关示例,请参阅具有唯一约束的部分索引

Sharded Clusters and Unique Indexes分片簇和唯一索引

You cannot specify a unique constraint on a hashed index.不能在哈希索引上指定唯一约束。

For a ranged sharded collection, only the following indexes can be unique:对于范围切分的集合,只有以下索引可以是唯一的:

  • the index on the shard key切分键上的索引
  • a compound index where the shard key is a prefix以分片键为前缀复合索引
  • the default _id index; however, the _id index only enforces the uniqueness constraint per shard if the _id field is not the shard key or the prefix of the shard key.默认的_id索引;但是,如果_id字段不是分片键或分片键的前缀,则_id索引仅对每个分片强制唯一性约束。

    Uniqueness and the _id Index唯一性和_id索引

    If the _id field is not the shard key or the prefix of the shard key, _id index only enforces the uniqueness constraint per shard and not across shards.如果_id字段不是分片键或分片键的前缀,则_id索引仅对每个分片强制唯一性约束,而不是跨多个分片强制唯一性约束。

    For example, consider a sharded collection (with shard key {x: 1}) that spans two shards A and B. 例如,考虑一个跨越两个碎片A和B的锐化集合(具有分片键{x:1 })。Because the _id key is not part of the shard key, the collection could have a document with _id value 1 in shard A and another document with _id value 1 in shard B.因为_id键不是分片键的一部分,集合可以在分片A中具有一个具有_id1的文档,并且在分片B中也有一个具有_id1的文档。

    If the _id field is not the shard key nor the prefix of the shard key, MongoDB expects applications to enforce the uniqueness of the _id values across the shards.如果_id字段既不是分片键,也不是分片键的前缀,MongoDB希望应用程序在各个分片上强制执行_id值的唯一性。

The unique index constraints mean that:独特的索引约束意味着:

  • For a to-be-sharded collection, you cannot shard the collection if the collection has other unique indexes.对于要切分的集合,如果该集合具有其他唯一索引,则无法切分该集合。
  • For an already-sharded collection, you cannot create unique indexes on other fields.对于已切分的集合,不能在其他字段上创建唯一索引。