Computer >> 컴퓨터 >  >> 프로그래밍 >> MongoDB

MongoDB에서 중복 없이 문서 삽입하기: 유니크(unique) 인덱스 활용법

MongoDB에 데이터를 삽입할 때 중복 레코드가 저장되는 것을 방지하려면 유니크(unique) 인덱스를 활용해야 합니다. 컬렉션 생성 시 인덱스 옵션에 unique: true를 설정하면, 해당 필드에 동일한 값이 다시 삽입될 때 데이터베이스가 자동으로 이를 거부합니다.

1단계: 유니크 인덱스가 설정된 컬렉션 만들기

먼저 createIndex() 메서드를 사용해 StudentFirstName 필드에 유니크 인덱스를 생성합니다. 이때 컬렉션이 존재하지 않으면 자동으로 함께 생성됩니다.

> db.insertWithoutDuplicateDemo.createIndex({"StudentFirstName":1},{ unique: true } );
{
    "createdCollectionAutomatically" : true,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1
}

2단계: 문서 삽입 및 중복 확인

이제 문서를 삽입해 보겠습니다. 처음 두 개의 문서는 서로 다른 이름을 가지고 있으므로 정상적으로 삽입됩니다.

> db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"Chris"},{ upsert: true });
WriteResult({ "nInserted" : 1 })
> db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"David"},{ upsert: true });
WriteResult({ "nInserted" : 1 })

그러나 이미 존재하는 값인 “Chris”를 다시 삽입하면 어떻게 될까요? 유니크 인덱스가 이를 감지하고 에러 코드 11000(E11000 duplicate key error)과 함께 삽입을 차단합니다.

> db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"Chris"},{ upsert: true });
WriteResult({
    "nInserted" : 0,
    "writeError" : {
        "code" : 11000,
        "errmsg" : "E11000 duplicate key error collection: test.insertWithoutDuplicateDemo index: StudentFirstName_1 dup key: { : \"Chris\" }"
    }
})

반면, 새로운 값인 “Bob”은 기존 데이터와 중복되지 않기 때문에 문제없이 저장됩니다.

> db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"Bob"},{ upsert: true });
WriteResult({ "nInserted" : 1 })

3단계: find()로 결과 검증하기

find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 조회할 수 있습니다.

> db.insertWithoutDuplicateDemo.find().pretty();

실행 결과는 다음과 같습니다. 중복된 “Chris”는 하나만 저장되어 있는 것을 확인할 수 있습니다.

{
    "_id" : ObjectId("5e064405150ee0e76c06a054"),
    "StudentFirstName" : "Chris"
}
{
    "_id" : ObjectId("5e064410150ee0e76c06a055"),
    "StudentFirstName" : "David"
}
{ "_id" : ObjectId("5e06441f150ee0e76c06a057"), "StudentFirstName" : "Bob" }

정리 및 참고 사항

  • unique: true 옵션은 해당 필드의 값이 컬렉션 내에서 항상 고유하도록 강제합니다.
  • 중복 키 오류 발생 시 반환되는 에러 코드는 11000입니다. 애플리케이션에서 이 코드를 catch하여 적절히 예외 처리할 수 있습니다.
  • 예제에서 사용된 upsert: true 옵션은 일치하는 문서가 없을 때 새로 삽입(insert), 있을 때 갱신(update)하도록 동작하지만, 유니크 제약 조건에는 영향을 주지 않습니다.
  • 여러 필드를 조합한 복합(composite) 유니크 인덱스도 가능하므로, 두 개 이상의 필드 조합이 고유해야 하는 경우에 활용할 수 있습니다.