Database Manual / Indexes / Properties / Unique

Convert an Existing Index to a Unique Index将现有索引转换为唯一索引

To convert a non-unique index to a unique index, use the collMod command. The collMod command provides options to verify that your indexed field contains unique values before you complete the conversion.要将非唯一索引转换为唯一索引,请使用collMod命令。collMod命令提供了在完成转换之前验证索引字段是否包含唯一值的选项。

Before you Begin开始之前

1

Populate sample data填充样本数据

Create the apples collection:创建apples集合:

db.apples.insertMany( [
{ type: "Delicious", quantity: 12 },
{ type: "Macintosh", quantity: 13 },
{ type: "Delicious", quantity: 13 },
{ type: "Fuji", quantity: 15 },
{ type: "Washington", quantity: 10 }
] )
2

Create a single field index创建单个字段索引

Add a single field index on the type field:type字段上添加单个字段索引:

db.apples.createIndex( { type: 1 } )

Steps步骤

1

Prepare the index to be converted to a unique index准备要转换为唯一索引的索引

Run collMod on the type field index and set prepareUnique to true:type字段索引上运行collMod,并将prepareUnique设置为true

db.runCommand( {
collMod: "apples",
index: {
keyPattern: { type: 1 },
prepareUnique: true
}
} )

After prepareUnique is set, you cannot insert new documents that duplicate an index key entry. For example, the following insert operation results in an error:设置prepareUnique后,您将无法插入重复索引键条目的新文档。例如,以下插入操作会导致错误:

db.apples.insertOne( { type: "Delicious", quantity: 20 } )
MongoServerError: E11000 duplicate key error collection:
test.apples index: type_1 dup key: { type: "Delicious" }
2

Check for unique key violations检查是否存在唯一键违规

To see if there are any documents that violate the unique constraint on the type field, run collMod with unique: true and dryRun: true:要查看是否有任何文档违反了类型字段的唯一约束,请使用unique:truedryRun:true运行collMod

db.runCommand( {
collMod: "apples",
index: {
keyPattern: { type: 1 },
unique: true
},
dryRun: true
} )
MongoServerError: Cannot convert the index to unique. Please resolve conflicting documents before running collMod again.

Violations: [
{
ids: [
ObjectId("660489d24cabd75abebadbd0"),
ObjectId("660489d24cabd75abebadbd2")
]
}
]
3

Resolve duplicate key conflicts解决重复键冲突

To complete the conversion, modify the duplicate entries to remove any conflicts. For example:要完成转换,请修改重复条目以消除任何冲突。例如:

db.apples.deleteOne(
{ _id: ObjectId("660489d24cabd75abebadbd2") }
)
4

Confirm that all conflicts are resolved确认所有冲突均已解决

To confirm that the index can be converted, re-run the collMod() command with dryRun: true:要确认索引可以转换,请使用dryRun:true重新运行collMod()命令:

db.runCommand( {
collMod: "apples",
index: {
keyPattern: { type: 1 },
unique: true
},
dryRun: true
} )
{ ok: 1 }
5

Finalize the index conversion完成索引转换

To finalize the conversion to a unique index, run the collMod command with unique: true and remove the dryRun flag:要完成向唯一索引的转换,请使用unique:true运行collMod命令并删除dryRun标志:

db.runCommand( {
collMod: "apples",
index: {
keyPattern: { type: 1 },
unique: true
}
} )
{ unique_new: true, ok: 1 }

Learn More了解更多