本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
索引屬性:唯一
支援的索引類型
| 選項 | 3.6 | 4.0 | 5.0 | 8.0 | 彈性叢集 |
|---|---|---|---|---|---|
| 單一欄位 | 是 | 是 | 是 | 是 | 是 |
| compound | 是 | 是 | 是 | 是 | 是 |
| 多金鑰 | 是 | 是 | 是 | 是 | 是 |
使用唯一選項來確保集合中文件間 欄位的唯一性 (含)。
範例
下列範例示範如何在下列範例文件上建立唯一索引:
{ "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": [ 1, 2, 3] } { "values": [ 3, 2 ] } --> 3 and 2 already exist { "values": [ 1 ] } --> 1 already exists
請注意具有唯一索引的下列行為:
如果您在現有資料上建立唯一索引,其中兩個 (或更多) 文件的索引欄位值相同,則索引建置將會失敗,並出現下列錯誤:
could not create unique index: <collection> index: <index name>如果您插入的文件的索引欄位值與另一個文件中該欄位的值相符,則插入會失敗,並顯示下列錯誤:
E11000 duplicate key error collection: <collection> index: <index name>如果您更新現有的文件,使索引欄位的新值與另一個文件中該欄位的值相符,則更新會失敗,並顯示下列錯誤:
E11000 duplicate key error collection: <collection> index: <index name>如果文件中缺少索引欄位,則值會視為 null。如果兩個 (或更多) 文件缺少索引欄位,索引建置、插入和更新將會失敗,如上所述。