非一意のインデックスを一意のインデックス に変換するには、 collModコマンドを使用します。 collModコマンドには、変換を完了する前にインデックス フィールドに一意の 値が含まれていることを確認するオプションが用意されています。
始める前に
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
4