文档菜单
文档首页
/
MongoDB 手册
/ / /

将现有索引转换为唯一索引

本页内容

  • 开始之前
  • 步骤
  • 了解更多

要将非唯一索引转换为唯一索引,请使用 collMod 命令。在完成转换之前,collMod 命令提供了选项以验证您的索引字段是否包含唯一值。

1

创建 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

type 字段上添加单个字段索引

db.apples.createIndex( { type: 1 } )
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 字段唯一约束的文档,请使用 collMod 并设置 unique: truedryRun: true

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

要完成转换,修改重复条目以消除任何冲突。例如

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

为了确认索引可以转换,重新运行带有 dryRun: truecollMod() 命令

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

为了最终将转换成唯一索引,运行带有 unique: truecollMod 命令并移除 dryRun 标志

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

返回

唯一