Docs Menu
Docs Home
/
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を実行し、 prepareUniquetrueに設定します。

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: 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

変換を完了するには、重複するエントリを変更して競合を排除します。 例:

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

インデックスが変換できることを確認するには、 dryRun: trueを使用してcollMod()コマンドを再実行します。

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

一意のインデックスへの変換を確定するには、 unique: trueを指定してcollModコマンドを実行し、 dryRunフラグを削除します。

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

戻る

Unique