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. 唯一索引确保索引字段不存储重复值;ie.强制索引字段的唯一性。By default, MongoDB creates a unique index on the _id field during the creation of a collection.默认情况下,MongoDB在创建集合期间在_id字段上创建唯一索引。

Note注意
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 mongosh:例如,要在members集合的user_id字段上创建唯一索引,请在mongosh中使用以下操作:

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 mongosh:例如,要在members集合的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值组合的唯一性。

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.insertMany( [
   { _id: 2, a: [ { loc: "A" }, { qty: 5 } ] },
   { _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.insertOne( { _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.insertOne( { 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.insertOne( { 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 }"
   }
})
Tip提示

Unique Partial Indexes唯一部分索引

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索引仅对每个分片强制唯一性约束。

    Important重要
    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. 例如,考虑一个分片集合(具有分片键{x:1}),它跨越两个分片a和B。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,其它_id值为1的文档在分片B中。。

    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.对于已分片的集合,不能在其他字段上创建唯一索引。

Sparse and Non-Sparse Unique Indexes稀疏和非稀疏唯一索引

Starting in MongoDB 5.0, unique sparse and unique non-sparse indexes with the same key pattern can exist on a single collection.从MongoDB 5.0开始,具有相同键模式唯一稀疏索引和唯一非稀疏索引可以存在于单个集合中。

Unique and Sparse Index Creation唯一和稀疏索引创建

This example creates multiple indexes with the same key pattern and different sparse options:此示例使用相同的键模式和不同的sparse选项创建多个索引:

db.scoreHistory.createIndex( { score : 1 }, { name: "unique_index", unique: true } )
db.scoreHistory.createIndex( { score : 1 }, { name: "unique_sparse_index", unique: true, sparse: true } )

Basic and Sparse Index Creation基本和稀疏索引创建

You can also create basic indexes with the same key pattern with and without the sparse option:您还可以使用相同的键模式创建基本索引,无论是否使用稀疏选项:

db.scoreHistory.createIndex( { score : 1 }, { name: "sparse_index", sparse: true } )
db.scoreHistory.createIndex( { score : 1 }, { name: "basic_index" } )

Basic and Unique Indexes With Duplicate Key Patterns具有重复键模式的基本索引和唯一索引

Starting in MongoDB 5.0, basic and unique indexes can exist with the same key pattern.从MongoDB 5.0开始,基本索引和唯一索引可以使用相同的键模式

This duplication in key patterns allows for adding a unique index to already indexed fields.键模式中的这种重复允许向已编制索引的字段添加唯一索引。

In this example:在此示例中:

Create a basic index with the key pattern { score : 1 } and insert three documents.使用键模式{ score : 1 }创建一个基本索引,并插入三个文档。

db.scoreHistory.createIndex( { score : 1 }, { name: "basic_index" } )
db.scoreHistory.insert( { score : 1 } )
db.scoreHistory.insert( { score : 2 } )
db.scoreHistory.insert( { score : 3 } )

Create a unique index with the same key pattern { score : 1 }.使用相同的键模式{ score : 1 }创建唯一索引。

db.scoreHistory.createIndex( { score : 1 }, { name: "unique_index", unique: true } )

Try to insert a duplicate score document that fails because of the unique index.尝试插入由于唯一索引而失败的重复score文档。

db.scoreHistory.insert( { score : 3 } )
←  Expire Data from Collections by Setting TTLPartial Indexes →