본문 바로가기
MongoDB/Evaluation Query Operators

[MongoDB] $jsonSchema

by 드름이 2022. 7. 1.

요약

- collection에서 특정 JSON 스키마를 충족하는 모든 document를 가져옵니다.

- collection에 특정 JSON 스키마를 설정하여 document들을 검증할 수 있습니다.

 


$jsonSchema의 query 예시입니다.

{
  $jsonSchema: {
     required: [ "이름", "전공", "평점", "주소" ],
     properties: {
        이름: {
           bsonType: "string",
           description: "필수입력 사항입니다."
        },
        주소: {
           bsonType: "object",
           required: [ "우편번호" ],
           properties: {
               "도로명": { bsonType: "string" },
               "우편번호": { bsonType: "string" }
           }
        }
     }
  }
}

 

몽고DB에서는 위에서 사용된 "required", "properties" 외에도 많은 키워드 집합을 제공합니다.

 

 

다양한 키워드를 사용하여 보다 복잡하고 정교한 JSON 스키마를 생성할 수 있습니다. 

 


1. 먼저 JSON 스키마를 만족시키는(또는 만족시키지 않는) documents를 찾아봅시다. 

 

 

아래 query 형식으로 찾을 수 있습니다. 

db.collection.find( { $jsonSchema: <schema> } )
db.collection.aggregate( [ { $match: { $jsonSchema: <schema> } } ] )
db.collection.updateMany( { $jsonSchema: <schema> }, <update> )
db.collection.deleteOne( { $jsonSchema: <schema> } )

 

 

JSON 스키마를 만족하지 않는 documents는 다음과 같은 형식으로 찾을 수 있습니다.

db.collection.find( { $nor: [ { $jsonSchema: <schema> } ] } )
db.collection.aggregate( [ { $match: { $nor: [ { $jsonSchema: <schema> } ] } }, ... ] )
db.collection.updateMany( { $nor: [ { $jsonSchema: <schema> } ] }, <update> )
db.collection.deleteOne( { $nor: [ { $jsonSchema: <schema> } ] } )

 

 


2. 이번에는 JSON 스키마를 collection에 등록하고 추가/업데이트 되는 document들을 점검하도록 해봅시다. 

 

 

우선 collection의 validator에 jsonSchema를 등록해야 합니다. (validator는 문서 검증기입니다)

 

 

"학생명단"이라는 collection을 생성한 뒤, validator에 아래와 같은 jsonSchema를 등록합니다.

 

 

db.createCollection("학생명단", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         required: [ "이름", "입학년도", "전공", "주소" ],
         properties: {
            이름: {
               bsonType: "string",
               description: "문자열 타입의 필수 항목입니다."
            },
            입학년도: {
               bsonType: "int",
               minimum: 2017,
               maximum: 3017,
               description: "[ 2017, 3017 ] 사이 정수 타입의 필수항목입니다."
            },
            전공: {
               enum: [ "수학", "영어", "컴퓨터공학", "역사", null ],
               description: "배열의 요소 중 하나이며, 필수 항목입니다."
            },
            평점: {
               bsonType: [ "int" ],
               description: "해당 필드가 존재한다면 값은 정수 타입입니다."
            },
            주소: {
               bsonType: "object",
               required: [ "도시" ],
               properties: {
                  도로명: {
                     bsonType: "string",
                     description: "해당 필드가 존재한다면 값은 문자열입니다."
                  },
                  도시: {
                     bsonType: "string",
                     "description": "문자열 타입의 필수 항목입니다."
                  }
               }
            }
         }
      }
   }
} )

 

곧바로 아래와 같은 document를 삽입하려고 합니다.

 

db.학생명단.insertOne( {
   이름: "앨리스",
   입학년도: Int32( 2019 ),
   전공: "역사",
   평점: "3",
   주소: {
      도시: "뉴욕",
      도로명: "33가"
   }
} )

 

결과는 어떨까요? 

 

학생명단이라는 collection에 등록되어있는 validator에서 해당 document를 검사하여 다음과 같은 오류를 던져줍니다.

 

MongoServerError: Document failed validation
Additional information: {
  failingDocumentId: ObjectId("61aa577f666a50a8fccd7ec2"),
  details: {
    operatorName: '$jsonSchema',
    schemaRulesNotSatisfied: [
      {
        operatorName: 'properties',
        propertiesNotSatisfied: [
          {
            propertyName: '평점',
            description: '해당 필드가 존재한다면 값은 정수 타입입니다.',
            details: [ [Object] ]
          }
        ]
      }
    ]
  }
}

 

에러가 발생한 document의 ID부터 시작해서 operator의 이름, 불일치한 schema 항목, 그 항목의 세부적인 내용까지 디테일하게 점검해줍니다. 

 

 

여기서는 '평점' 항목의 타입에 정수가 아닌 문자열이 들어가서 에러가 발생했군요.

 


프로젝트 규모가 커질수록 document 검증은 매우 큰 효과를 발휘할 것입니다.

 

 

 

출처: $jsonSchema — MongoDB Manual

'MongoDB > Evaluation Query Operators' 카테고리의 다른 글

[MongoDB] $regex  (0) 2022.07.01
[MongoDB] $mod  (0) 2022.07.01
[MongoDB] $expr  (0) 2022.07.01