$jsonSchema
이 페이지의 내용
정의
$jsonSchema
$jsonSchema
연산자는 지정된 JSON schema 를 충족하는 문서와 일치합니다.$jsonSchema
연산자 표현식 의 구문은 다음과 같습니다.{ $jsonSchema: <JSON Schema object> } 여기서 JSON schema 객체 의 형식 은 표준 의 초안 4 에 따라 JSON schema 지정됩니다. .
{ <keyword1>: <value1>, ... } 예를 들면 다음과 같습니다.
{ $jsonSchema: { required: [ "name", "major", "gpa", "address" ], properties: { name: { bsonType: "string", description: "must be a string and is required" }, address: { bsonType: "object", required: [ "zipcode" ], properties: { "street": { bsonType: "string" }, "zipcode": { bsonType: "string" } } } } } } MongoDB 에서 지원하는 키워드 목록은 사용 가능한 키워드를 참조하세요.
참고
MongoDB 4 JSON schema는 핵심 사양 을 포함하여 의 초안을 지원합니다. 및 유효성 검사 사양, 몇 가지 차이점이 있습니다. 자세한 내용은 확장 및 생략 을 참조하세요.
에 대한 JSON schema 자세한 내용은 공식 웹사이트 를 참조하세요. .
행동
기능 호환성
$jsonSchema
를 사용하려면featureCompatibilityVersion을 이상으로 설정하다 해야 합니다. "3.6"
문서 유효성 검사기
문서 유효성 검사기에서 $jsonSchema
를 사용하여 삽입 및 업데이트 작업에 지정된 스키마 를 시행하다 수 있습니다.
db.createCollection( <collection>, { validator: { $jsonSchema: <schema> } } ) db.runCommand( { collMod: <collection>, validator:{ $jsonSchema: <schema> } } )
쿼리 조건
읽기 및 쓰기 (write) 작업에 대한 쿼리 조건에서 $jsonSchema
를 사용하여 컬렉션 에서 지정된 스키마 를 충족하는 문서를 찾을 수 있습니다.
db.collection.find( { $jsonSchema: <schema> } ) db.collection.aggregate( [ { $match: { $jsonSchema: <schema> } } ] ) db.collection.updateMany( { $jsonSchema: <schema> }, <update> ) db.collection.deleteOne( { $jsonSchema: <schema> } )
To find documents in the collection that do not satisfy the specified schema, use the $jsonSchema
expression in a $nor
expression. 예를 예시 다음과 같습니다.
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> } ] } )
예시
스키마 유효성 검사
다음 db.createCollection()
메서드는 students
이라는 컬렉션을 생성하고 $jsonSchema
연산자를 사용하여 스키마 유효성 검사 규칙을 설정합니다.
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" }, major: { enum: [ "Math", "English", "Computer Science", "History", null ], description: "can only be one of the enum values and is required" }, gpa: { bsonType: [ "double" ], description: "must be a double if the field exists" }, address: { bsonType: "object", required: [ "city" ], properties: { street: { bsonType: "string", description: "must be a string if the field exists" }, city: { bsonType: "string", "description": "must be a string and is required" } } } } } } } )
컬렉션에 대해 생성된 validator
가 주어지면 validator
에 double
이 필요한 경우 gpa
이 정수이기 때문에 다음 삽입 작업이 실패합니다.
db.students.insertOne( { name: "Alice", year: Int32( 2019 ), major: "History", gpa: Int32( 3 ), address: { city: "NYC", street: "33rd Street" } } )
이 작업은 다음 오류를 반환합니다.
MongoServerError: Document failed validation Additional information: { failingDocumentId: ObjectId("61aa577f666a50a8fccd7ec2"), details: { operatorName: '$jsonSchema', schemaRulesNotSatisfied: [ { operatorName: 'properties', propertiesNotSatisfied: [ { propertyName: 'gpa', description: 'must be a double if the field exists', details: [ [Object] ] } ] } ] } }
gpa
을(를) double로 변경하면 삽입이 성공합니다.
db.students.insertOne( { name: "Alice", year: NumberInt(2019), major: "History", gpa: Double(3.0), address: { city: "NYC", street: "33rd Street" } } )
쿼리 조건
읽기 및 쓰기 (write) 작업에 대한 쿼리 조건에서 $jsonSchema
를 사용하여 컬렉션 에서 지정된 스키마 를 충족하는 문서를 찾을 수 있습니다.
예를 들어 다음 문서를 사용하여 샘플 컬렉션 inventory
을 만듭니다.
db.inventory.insertMany( [ { item: "journal", qty: NumberInt(25), size: { h: 14, w: 21, uom: "cm" }, instock: true }, { item: "notebook", qty: NumberInt(50), size: { h: 8.5, w: 11, uom: "in" }, instock: true }, { item: "paper", qty: NumberInt(100), size: { h: 8.5, w: 11, uom: "in" }, instock: 1 }, { item: "planner", qty: NumberInt(75), size: { h: 22.85, w: 30, uom: "cm" }, instock: 1 }, { item: "postcard", qty: NumberInt(45), size: { h: 10, w: 15.25, uom: "cm" }, instock: true }, { item: "apple", qty: NumberInt(45), status: "A", instock: true }, { item: "pears", qty: NumberInt(50), status: "A", instock: true } ] )
다음으로, 다음 샘플 스키마 객체 를 정의합니다.
let myschema = { required: [ "item", "qty", "instock" ], properties: { item: { bsonType: "string" }, qty: { bsonType: "int" }, size: { bsonType: "object", required: [ "uom" ], properties: { uom: { bsonType: "string" }, h: { bsonType: "double" }, w: { bsonType: "double" } } }, instock: { bsonType: "bool" } } }
$jsonSchema
를 사용하여 스키마 를 충족하는 컬렉션 의 모든 문서를 찾을 수 있습니다.
db.inventory.find( { $jsonSchema: myschema } ) db.inventory.aggregate( [ { $match: { $jsonSchema: myschema } } ] )
$jsonSchema
을 $nor
}와 함께 사용하여 스키마를 충족하지 않는 모든 문서를 찾을 수 있습니다.
db.inventory.find( { $nor: [ { $jsonSchema: myschema } ] } )
또는 스키마를 충족하지 않는 모든 문서를 업데이트할 수 있습니다.
db.inventory.updateMany( { $nor: [ { $jsonSchema: myschema } ] }, { $set: { isValid: false } } )
또는 스키마 를 충족하지 않는 모든 문서를 삭제 수 있습니다.
db.inventory.deleteMany( { $nor: [ { $jsonSchema: myschema } ] } )
JSON Schema
MongoDB 4 JSON schema는 핵심 사양 을 포함하여 의 초안을 지원합니다. 및 유효성 검사 사양, 몇 가지 차이점이 있습니다. 자세한 내용은 확장 및 생략 을 참조하세요.
에 대한 JSON schema 자세한 내용은 공식 웹사이트 를 참조하세요. .
사용 가능한 키워드
참고
MongoDB는 JSON Schema에서 사용할 수 있는 키워드의 하위 세트를 구현합니다. 누락된 항목의 전체 목록은 누락 항목을 참조하세요.
Keyword | 유형 | 정의 | 행동 |
---|---|---|---|
bsonType | 모든 유형 | 문자열 별칭 또는 문자열 별칭 배열 | |
열거형 | 모든 유형 | 값 배열 | 필드의 사용 가능한 값을 모두 열거합니다. |
유형 | 모든 유형 | 문자열 또는 고유 문자열 배열 | 필드의 사용 가능한 JSON 유형을 열거합니다. 사용 가능한 유형은 "객체", "배열", "숫자", "부울", "문자열", "null"입니다. MongoDB의 JSON Schema 구현 기능은 "정수" 유형을 지원하지 않습니다. 대신 |
allOf | 모든 유형 | JSON Schema 객체 배열 | 필드가 지정된 모든 스키마와 일치해야 합니다. |
anyOf | 모든 유형 | JSON Schema 객체 배열 | 필드가 지정된 스키마 중 1개 이상과 일치해야 합니다. |
oneOf | 모든 유형 | JSON Schema 객체 배열 | 필드가 지정된 스키마 중 1개와 정확히 일치해야 합니다. |
not | 모든 유형 | JSON Schema 객체 | 필드가 스키마와 일치하지 않아야 합니다. |
multipleOf | 숫자 | 숫자 | 필드가 이 값의 배수여야 합니다. |
maximum | 숫자 | 숫자 | 필드의 최댓값을 나타냅니다. |
exclusiveMaximum | 숫자 | 부울 | true(참)이고 필드가 숫자인 경우 |
minimum | 숫자 | 숫자 | 필드의 최솟값을 나타냅니다. |
exclusiveMinimum | 숫자 | 부울 | true(참)인 경우 |
maxLength | strings | integer | 필드의 최대 길이를 나타냅니다. |
minLength | strings | integer | 필드의 최소 길이를 나타냅니다. |
패턴 | strings | 정규 표현식이 포함된 문자열 | 필드가 정규 표현식과 일치해야 합니다. |
maxProperties | 객체 | integer | 필드의 최대 속성 수를 나타냅니다. |
minProperties | 객체 | integer | 필드의 최소 속성 수를 나타냅니다. |
필수 | 객체 | 고유 문자열 배열 | 배열에 지정된 모든 요소가 객체의 속성 세트에 포함되어야 합니다. |
additionalProperties | 객체 | 부울 또는 객체 |
기본값은 |
속성 | 객체 | 객체 | 각 값이 유효한 JSON Schema 객체이기도 한 유효한 JSON Schema입니다. |
patternProperties | 객체 | 객체 |
|
dependencies | 객체 | 객체 | 필드 또는 스키마 종속성을 설명합니다. |
additionalItems | 배열 | 부울 또는 객체 | 객체인 경우 유효한 JSON Schema여야 합니다. |
항목 | 배열 | 객체 또는 배열 | 유효한 JSON Schema이거나 유효한 JSON Schema의 배열이어야 합니다. |
maxItems | 배열 | integer | 배열의 최대 길이를 나타냅니다. |
minItems | 배열 | integer | 배열의 최소 길이를 나타냅니다. |
uniqueItems | 배열 | 부울 | true(참)인 경우 배열의 각 항목은 고유해야 합니다. 그렇지 않은 경우에는 고유성 제약 조건이 적용되지 않습니다. |
제목 | N/A | 문자열 | 효과가 없는 서술형 제목 문자열입니다. |
description | N/A | 문자열 | 스키마 를 설명하며 아무런 효과가 없는 string 입니다. |
확장 프로그램
의 구현에는 $jsonSchema
연산자의 모든 types를 사용할 BSON MongoDB JSON schema 수 있는 bsonType
키워드 추가가 포함됩니다. 는 연산자에 $type
사용된 것과bsonType
동일한 별칭을 허용합니다.string
생략
MongoDB의 JSON Schema 구현 기능은 다음을 지원하지 않습니다.