AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.

기존 인덱스를 고유 인덱스로 변환

고유하지 않은 고유 인덱스 고유 인덱스 변환하려면 collMod 명령을 사용합니다. collMod 명령은 변환을 완료하기 전에 인덱싱된 필드 에 고유 값이 포함되어 있는지 확인하는 옵션을 제공합니다.

collMod 명령은 기존 인덱스를 변환합니다. MongoDB는 인덱스에서 중복 키를 검색한 다음 인덱스를 고유(unique)로 표시합니다.

인덱스를 변환할 때 다음 동작을 염두에 두십시오.

  • 인덱스를 변환하기 전에 prepareUnique을(를) true (으)로 설정하세요. prepareUnique이(가) false인 경우 unique: true을(를) 포함한 collMod은(는) 오류를 반환합니다.

  • 별도의 collMod 명령에서 prepareUnique 수정을 실행합니다. prepareUnique을(를) 다른 인덱스 수정과 결합할 수 없습니다.

  • Time Series 컬렉션의 인덱스에는 prepareUnique을(를) 설정할 수 없습니다. MongoDB가 오류를 반환합니다.

  • collMod이(가) 인덱스를 변환하는 동안 다른 작업이 인덱스를 수정하거나 제거하면 명령이 실패합니다. 다른 작업이 완료된 후 명령을 다시 실행하십시오.

샤딩된 컬렉션의 경우 다음 동작도 적용됩니다.

  • 샤드에 중복 키가 포함되어 있으면 collMod이(가) CannotConvertIndexToUnique을(를) 반환합니다. MongoDB는 어떤 샤드에서도 인덱스를 변환하지 않습니다.

  • 인덱스 키가 샤드 키와 충돌하면 prepareUnique 설정이 실패합니다. 샤딩된 컬렉션에서 어떤 인덱스가 고유할 수 있는지 알아보려면 샤딩된 클러스터 및 고유 인덱스를 참조하세요.

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 값이 포함된 응답이 8MB를 초과하는 경우 MongoDB는 특정 위반 사항을 나열하는 대신에 다음 오류 메시지를 반환합니다.

Cannot convert the index to unique. Too many conflicting documentswere 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 }