programing

MongoDB에서 두 개의 필드가 있는 고유 제약 조건

kakaobank 2023. 5. 12. 22:37
반응형

MongoDB에서 두 개의 필드가 있는 고유 제약 조건

"email" 및 "friends_email" 필드가 있는 컬렉션이 있습니다.MongoDB를 사용하여 다음과 같은 고유성 제약 조건을 설정하고 싶습니다.

  1. 전자 메일 및 friends_email에 대해 동일한 값을 가지는 레코드는 없습니다.따라서 이것은 유효하지 않습니다.

    {"email": "abc@example.com", "friends_email": "abc@example.com" }
    
  2. 모든 필드에 대해 동일한 값을 가지는 레코드는 두 개 없습니다.따라서 다음 예제는 모두 유효하지 않습니다.

    {
        { "email": "abc@example.com", "friends_email": "def@example.com" },
        { "email": "abc@example.com", "friends_email": "def@example.com" }
    }
    {
        { "email": "abc@example.com", "friends_email": null },
        { "email": "abc@example.com", "friends_email": null }
    }
    {
        { "email": null, "friends_email": "abc@example.com" },
        { "email": null, "friends_email": "abc@example.com" }
    }
    

    쉬운 영어로 말하자면, 그것은 다음과 같은 것일 것입니다.email그리고.friends_email고유할 것입니다.null그리고.undefined빈 문자열로 결합됩니다.

MongoDB에서 이 규칙을 시행하는 가장 좋은 방법은 무엇입니까?

복합 고유 인덱스가 필요한 것 같습니다.

db.users.createIndex( { "email": 1, "friends_email": 1 }, { unique: true } )

ORM 계층에서 이메일 =/= friends_email을 확인할 수 있습니다.

복합 고유 인덱스를 사용할 수 있습니다.email그리고.friends_email두 번째 경우를 보장하기 위한 필드.그러나 첫 번째 경우에는 애플리케이션 코드에서 이를 처리하거나 Morphia와 같은 Java 매퍼를 사용하여 현장 기반 검증을 수행해야 합니다.다음 게시물도 확인할 수 있습니다.

MongoDB에서 제약 조건을 적용하는 방법은 무엇입니까?

두 번째 경우, 고유한 복합 지수가 당신이 찾고 있는 것입니까?

 db.emails.ensureIndex( {email:1, friends_email:1}, { unique: true } )

첫 번째 경우에 대해서는, 첫 번째 규칙을 시행할 수 있는 방법이 있는지 잘 모르겠습니다.애플리케이션 측에서 검사를 수행해야 할 수도 있습니다.

#1의 경우 Schema Validaton을 사용하여 데이터베이스 측에 검사를 설정할 수 있습니다.

validator: {
  "$expr": {
    "$ne": [ "$email", "$friends_email" ]
  }
}

db.runCommand( { collMod: "collectionName", validator: validator} )

언급URL : https://stackoverflow.com/questions/14692726/unique-constraint-with-two-fields-in-mongodb

반응형