

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 索引属性：唯一
<a name="index-property-unique"></a>

## 支持的索引类型
<a name="index-property-unique-supported"></a>


| Option | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
| 单字段 | 支持 | 是 | 是 | 是 | 是 | 
| 复合排序 | 支持 | 是 | 是 | 是 | 是 | 
| 多键 | 支持 | 是 | 是 | 是 | 是 | 

使用 unique 选项可确保集合中各文档中各字段的唯一性。

## 示例
<a name="index-property-unique-examples"></a>

以下示例说明如何在以下示例文档中创建唯一索引：

```
{
  "productId": "PROD133726",
  "sku": "SKU24224",
  "name": "Basic Printer",
  "manufacturer": "The Manufacturer",
  "tags": [ "printer", "basic", "electronics", "business" ],
  "barcodes": [ "542364671", "886330670", "437445606" ],
  "reviews": [
    {
      "review_date": ISODate('2024-01-19T21:37:10.585Z'),
      ...
    }
  ],
  "material": "Polycarbonate",
  "color": "Space Gray",
  "supplier": {
    "supplierId": "SUP4",
    "location": {
      "type": "Point",
      "coordinates": [ -71.0589, 42.3601 ]
    }
  },
  "productEmbedding": [
    -0.019320633663838058,
    0.019672111388113596
  ],
  "lastUpdated": ISODate('2025-10-20T21:37:10.585Z')
}
```

单字段

在 ProductID 上创建唯一的单字段索引，以确保同一个 productID 不存在于多个 1 个文档中：

```
db.collection.createIndex(
  {
    "productId": 1
  },
  {
    name: "productId_unique",
    unique: true
  }
)
```

化合物

在 SKU 和制造商上创建唯一的复合索引，以确保在多个 1 个文档中不存在相同的 SKU 和制造商组合：

```
db.collection.createIndex(
  {
    "sku": 1,
    "manufacturer": 1
  },
  {
    name: "sku_and_manufacturer_unique",
    unique: true
  }
)
```

多键

在条形码上创建唯一的多键索引，以确保条形码数组中的任何值不存在于超过 1 个文档中：

```
db.collection.createIndex(
  {
    "barcodes": 1
  },
  {
    name: "barcodes_unique",
    unique: true
  }
)
```

对数组进行索引会为数组的每个元素创建一个索引条目。例如，如果一个数组有 50 个项目，则它有 50 个索引条目。因此，唯一的多键索引强制所有单个项目的唯一性。例如，以下文档将违反 values 数组字段索引的唯一约束：

```
{ "values": [ 1, 2, 3] }
{ "values": [ 3, 2 ] }   --> 3 and 2 already exist
{ "values": [ 1 ] }      --> 1 already exists
```

请注意具有唯一索引的以下行为：

1. 如果您在现有数据上创建唯一索引，其中两个（或更多）文档的索引字段值相同，则索引构建将失败，并显示以下错误：`could not create unique index: <collection> index: <index name>`

1. 如果您插入的文档中索引字段的值与另一个文档中该字段的值相匹配，则插入操作将失败，并显示以下错误：`E11000 duplicate key error collection: <collection> index: <index name>`

1. 如果您更新现有文档，使索引字段的新值与其他文档中该字段的值相匹配，则更新将失败并显示以下错误：`E11000 duplicate key error collection: <collection> index: <index name>`

1. 如果文档中缺少索引字段，则该值将被视为空。如果两个（或更多）文档中缺少索引字段，则如上所述，索引构建、插入和更新将失败。