要将非唯一索引转换为唯一索引,请使用collMod命令。 collMod命令提供了一些选项,用于在完成转换之前验证索引字段是否包含唯一值。
开始之前
步骤
1
准备要转换为唯一索引的索引
在 type 字段索引上运行 collMod 并将 prepareUnique 设置为 true:
db.runCommand( { collMod: "apples", index: { keyPattern: { type: 1 }, prepareUnique: true } } )
设置 prepareUnique 后,您将无法插入与索引键条目重复的新文档。例如,以下插入操作会导致错误:
db.apples.insertOne( { type: "Delicious", quantity: 20 } )
MongoServerError: E11000 duplicate key error collection: test.apples index: type_1 dup key: { type: "Delicious" }
2
检查唯一键违规
要查看是否有任何文档违反了 type 字段的唯一约束,请使用 unique: true 和 dryRun: 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") ] } ]
注意
如果包含所有冲突文档_id 值的响应超过 8MB,则MongoDB返回以下错误消息,而不是列出具体的违规行为:
Cannot convert the index to unique. Too many conflicting documents were detected. Please resolve them and rerun collMod.
在这种情况下,请解决重复条目,直到响应低于 8MB,然后再次运行collMod 以查看剩余的违规情况。
4