AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
See how MongoDB 9.0 delivers up to 2x higher throughput.
MongoDB Branding Shape
Register now >
Docs Menu

既存のインデックスをユニークインデックスに変換する

非一意のインデックスを一意のインデックス に変換するには、 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フィールドの一意の制約に違反するドキュメントがあるかどうかを確認するには、 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 値を含む応答が 8 MB を超える場合、特定の違反をリストする代わりに、 MongoDB は次のエラーメッセージを返します。

Cannot convert the index to unique. Too many conflicting documents
were detected. Please resolve them and rerun collMod.

この場合は、レスポンスが 8MB 未満になるまで重複エントリを解決し、collMod を再度実行して残りの違反を確認します。

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 }
このページを評価