문서 메뉴
문서 홈
/
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 }

돌아가기

유일한

다음

빌드