일부 상황에서는 컬렉션의 스키마 유효성 검사 규칙을 우회해야 할 수도 있습니다. 예를 들어 유효하지 않을 수 있는 데이터를 백업에서 유효성 검사 규칙이 있는 컬렉션으로 복원하는 경우를 들 수 있습니다. 이 시나리오에서는 오래된 문서가 새로운 유효성 검사 요건을 충족하지 못할 수 있습니다.
Context
스키마 유효성 검사 우회는 작업별로 수행됩니다. 스키마 유효성 검사를 우회하여 잘못된 문서를 삽입하는 경우 잘못된 문서에 대한 향후 업데이트는 다음 중 하나를 수행해야 합니다.
스키마 유효성 검사도 우회합니다.
유효한 문서를 생성합니다.
유효성 검사 수준 제한
컬렉션의 validationLevel이(가) constraint이거나 prepareConstraintValidationLevel이(가) true인 경우, MongoDB는 bypassDocumentValidation을(를) true(으)로 설정하는 모든 쓰기 (write) 작업을 거부합니다. 문서가 유효성 검사 규칙을 충족하는 경우에도 쓰기 (write) 작업은 실패합니다.
{ ok: 0, errmsg: "bypassDocumentValidation is not permitted with 'constraint' validationLevel", code: 2, codeName: "BadValue"}prepareConstraintValidationLevel이(가) true인 경우, 쓰기 (write)는 다른 메시지와 함께 실패합니다. 해당 메시지는 prepareConstraintValidationLevel을(를) 명시하고 이를 지우는 명령을 제공합니다. 두 실패 모두 BadValue 오류 코드를 사용합니다.
유효성 검사를 우회하는 기능을 복원하려면 collMod:를 사용하여 컬렉션을 업데이트하세요.
컬렉션의
validationLevel이(가)constraint인 경우strict(으)로 설정합니다.컬렉션의
prepareConstraintValidationLevel이(가)true인 경우false(으)로 설정합니다.
버전 9.0에 추가 되었습니다.
지원되는 작업
다음 명령과 메서드를 사용하여 작업별로 유효성 검사를 우회할 수 있습니다.
applyOps명령mapReduce명령 및db.collection.mapReduce()메서드insert명령update명령aggregate명령 및db.collection.aggregate()메서드에 대한$out및$merge단계
전제 조건
액세스 제어를 활성화한 배포의 경우 문서 유효성 검사를 우회하려면 인증된 사용자에게 bypassDocumentValidation 작업이 있어야 합니다. 기본 제공 역할 dbAdmin 및 restore가 이 작업을 제공합니다.
단계
다음 예시에서는 스키마 유효성 검사를 사용하여 컬렉션을 만든 다음 유효성 검사 규칙을 우회하여 잘못된 문서를 삽입합니다.
유효성 검사 규칙을 사용하여 컬렉션 만들기
0} 컬렉션을 $jsonSchema 만들고 students 연산자를 사용하여 스키마 유효성 검사 규칙을 설정합니다.
db.createCollection("students", { validator: { $jsonSchema: { bsonType: "object", required: [ "name", "year", "major", "address" ], properties: { name: { bsonType: "string", description: "must be a string and is required" }, year: { bsonType: "int", minimum: 2017, maximum: 3017, description: "must be an integer in [ 2017, 3017 ] and is required" } } } }} )유효성 검사를 우회하여 잘못된 문서 삽입하기
year 필드가 허용된 범위(2017-3017)를 벗어났기 때문에 다음 문서는 유효하지 않습니다.
{ name: "Alice", year: Int32( 2016 ), major: "History", gpa: Double(3.0), address: { city: "NYC", street: "33rd Street" }}유효성 검사 규칙을 우회하고 잘못된 문서를 삽입하려면 다음 insert 명령을 실행합니다. 이 명령은 bypassDocumentValidation 옵션을 true로 설정합니다.
db.runCommand( { insert: "students", documents: [ { name: "Alice", year: Int32( 2016 ), major: "History", gpa: Double(3.0), address: { city: "NYC", street: "33rd Street" } } ], bypassDocumentValidation: true} )결과
문서가 성공적으로 삽입되었는지 확인하려면 students 컬렉션을 쿼리합니다.
db.students.find()MongoDB는 삽입된 문서를 반환합니다.
[ { _id: ObjectId("62bcb4db3f7991ea4fc6830e"), name: 'Alice', year: 2016, major: 'History', gpa: 3, address: { city: 'NYC', street: '33rd Street' } }]