고유하지 않은 고유 인덱스 고유 인덱스 변환하려면 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 값을 포함하는 응답이 8MB를 초과하는 경우, MongoDB 특정 위반 사항을 나열하는 대신 다음 오류 메시지를 반환합니다.
Cannot convert the index to unique. Too many conflicting documents were detected. Please resolve them and rerun collMod.
이 경우 응답이 8MB 미만이 될 때까지 중복 항목을 해결한 다음 collMod를 다시 실행 나머지 위반 사항을 확인합니다.
3
4