

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# JSON 스키마 검증 사용
<a name="json-schema-validation"></a>

`$jsonSchema`평가 쿼리 연산자를 사용하여, 컬렉션에 삽입되는 문서를 검증할 수 있습니다.

**Topics**
+ [JSON 스키마 검증 생성 및 사용](#get-started-with-validation)
+ [지원되는 키워드](#json-supported-keywords)
+ [bypassDocumentValidation](#json-schema-bypass)
+ [제한 사항](#json-schema-limitations)

## JSON 스키마 검증 생성 및 사용
<a name="get-started-with-validation"></a>

### 스키마 검증을 통한 컬렉션 만들기
<a name="create-collection-with-validation"></a>

`createCollection`작업 및 검증 규칙을 사용하여 컬렉션을 만들 수 있습니다. 이러한 검증 규칙은 Amazon DocumentDB 문서를 삽입하거나 업데이트할 때 적용됩니다. 다음 코드 예제에서는 직원 컬렉션에 대한 검증 규칙을 보여줍니다:

```
db.createCollection("employees", {
   "validator": {
      "$jsonSchema": {
         "bsonType": "object",
         "title": "employee validation",
         "required": [ "name", "employeeId"],
         "properties": {
            "name": {
                  "bsonType": "object",
                  "properties": {
                     "firstName": {
                        "bsonType": ["string"]
                     },
                     "lastName": {
                        "bsonType": ["string"]
                     }
                  },
                  "additionalProperties" : false 
            },
            "employeeId": {
               "bsonType": "string",
               "description": "Unique Identifier for employee"
            },
             "salary": {
               "bsonType": "double"
            },
            "age": {
               "bsonType": "number"
            }
         },
         "additionalProperties" : true 
      }
   },
   "validationLevel": "strict", "validationAction": "error"
} )
```

### 유효한 문서 삽입
<a name="insert-valid-document"></a>

다음 예제는 위의 스키마 검증 규칙을 준수하는 문서를 삽입합니다:

```
db.employees.insert({"name" : { "firstName" : "Carol" , "lastName" : "Smith"}, "employeeId": "c720a" , "salary": 1000.0 })
db.employees.insert({ "name" : { "firstName" : "William", "lastName" : "Taylor" }, "employeeId" : "c721a", "age" : 24})
```

### 잘못된 문서 삽입
<a name="insert-invalid-document"></a>

다음 예제에서는 위 스키마 유효성 검사 규칙을 준수하지 않는 문서를 삽입합니다. 이 예제에서 employeeId 값은 문자열이 아닙니다:

```
db.employees.insert({
    "name" : { "firstName" : "Carol" , "lastName" : "Smith"}, 
    "employeeId": 720 , 
    "salary": 1000.0 
})
```

이 예제는 문서 내의 잘못된 구문을 보여줍니다.

### 컬렉션 수정
<a name="modify-collection"></a>

이 `collMod` 명령은 기존 컬렉션의 검증 규칙을 추가하거나 수정하는 데 사용됩니다. 다음 예제에서는 필수 필드 목록에 급여 필드를 추가합니다:

```
db.runCommand({"collMod" : "employees", 
   "validator": {
      "$jsonSchema": {
         "bsonType": "object",
         "title": "employee validation",
         "required": [ "name", "employeeId", "salary"],
         "properties": {
            "name": {
                  "bsonType": "object",
                  "properties": {
                     "firstName": {
                        "bsonType": ["string"]
                     },
                     "lastName": {
                        "bsonType": ["string"]
                     }
                  },
                  "additionalProperties" : false 
            },
            "employeeId": {
               "bsonType": "string",
               "description": "Unique Identifier for employee"
            },
             "salary": {
               "bsonType": "double"
            },
            "age": {
               "bsonType": "number"
            }
         },
         "additionalProperties" : true 
      }
   }
} )
```

### 검증 규칙이 변경되기 전에 추가된 주소 지정 문서
<a name="pre-validation-docs"></a>

검증 규칙이 변경되기 전에 컬렉션에 추가된 문서의 주소를 지정하려면 다음 `validationLevel` 수정자를 사용하십시오:
+ **엄격**: 모든 삽입 및 업데이트에 검증 규칙을 적용합니다.
+ **보통**: 기존의 유효한 문서에 검증 규칙을 적용합니다. 업데이트하는 동안 기존의 잘못된 문서는 확인되지 않습니다.

다음 예제에서는 “employees”라는 이름의 컬렉션에 대한 검증 규칙을 업데이트한 후 급여 필드가 필수입니다. 다음 문서 업데이트는 실패합니다:

```
db.runCommand({ 
    update: "employees", 
    updates: [{ 
        q: { "employeeId": "c721a" }, 
        u: { age: 25 , salary : 1000}, 
        upsert: true }] 
})
```

Amazon DocumentDB는 다음 출력을 반환합니다:

```
{
"n" : 0,
    "nModified" : 0,
    "writeErrors" : [
        {
"index" : 0,
            "code" : 121,
            "errmsg" : "Document failed validation"
        }
    ],
    "ok" : 1,
    "operationTime" : Timestamp(1234567890, 1)
}
```

검증 수준을 `moderate`로 업데이트하면 위 문서가 성공적으로 업데이트될 수 있습니다:

```
db.runCommand({
    "collMod" : "employees", 
    validationLevel : "moderate"
})

db.runCommand({ 
    update: "employees", 
    updates: [{ 
        q: { "employeeId": "c721a" }, 
        u: { age: 25 , salary : 1000}, 
        upsert: true }]
})
```

Amazon DocumentDB는 다음 출력을 반환합니다:

```
{
"n" : 1,
    "nModified" : 1,
    "ok" : 1,
    "operationTime" : Timestamp(1234567890, 1)
}
```

### \$1jsonSchema를 사용하여 문서 검색
<a name="json-retrieve-docs"></a>

`$jsonSchema`연산자를 필터로 사용하여 JSON schema와 일치하는 문서를 쿼리할 수 있습니다. 이것은 필터 문서에 최상위 필드로 존재하거나 `$and`, `$or`, 및 `$nor`과 같은 쿼리 연산자와 함께 사용할 수 있는 최상위 연산자입니다. 다음 예제는 \$1JSONSchema를 개별 필터 및 기타 필터 연산자와 함께 사용하는 방법을 보여줍니다:

“직원” 컬렉션에 삽입된 문서:

```
{ "name" : { "firstName" : "Carol", "lastName" : "Smith" }, "employeeId" : "c720a", "salary" : 1000 }
{ "name" : { "firstName" : "Emily", "lastName" : "Brown" }, "employeeId" : "c720b", "age" : 25, "salary" : 1050.2 }
{ "name" : { "firstName" : "William", "lastName" : "Taylor" }, "employeeId" : "c721a", "age" : 24, "salary" : 1400.5 }
{ "name" : { "firstName" : "Jane", "lastName" : "Doe" }, "employeeId" : "c721a", "salary" : 1300 }
```

`$jsonSchema`연산자로만 필터링된 컬렉션:

```
db.employees.find({ 
       $jsonSchema: { required: ["age"] } })
```

Amazon DocumentDB는 다음 출력을 반환합니다:

```
{ "_id" : ObjectId("64e5f91c6218c620cf0e8f8b"), "name" : { "firstName" : "Emily", "lastName" : "Brown" }, "employeeId" : "c720b", "age" : 25, "salary" : 1050.2 }
{ "_id" : ObjectId("64e5f94e6218c620cf0e8f8c"), "name" : { "firstName" : "William", "lastName" : "Taylor" }, "employeeId" : "c721a", "age" : 24, "salary" : 1400.5 }
```

`$jsonSchema`연산자와 다른 연산자로 필터링된 컬렉션:

```
db.employees.find({ 
       $or: [{ $jsonSchema: { required: ["age", "name"]}}, 
            { salary: { $lte:1000}}]});
```

Amazon DocumentDB는 다음 출력을 반환합니다:

```
{ "_id" : ObjectId("64e5f8886218c620cf0e8f8a"), "name" : { "firstName" : "Carol", "lastName" : "Smith" }, "employeeId" : "c720a", "salary" : 1000 }
{ "_id" : ObjectId("64e5f91c6218c620cf0e8f8b"), "name" : { "firstName" : "Emily", "lastName" : "Brown" }, "employeeId" : "c720b", "age" : 25, "salary" : 1050.2 }
{ "_id" : ObjectId("64e5f94e6218c620cf0e8f8c"), "name" : { "firstName" : "William", "lastName" : "Taylor" }, "employeeId" : "c721a", "age" : 24, "salary" : 1400.5 }
```

`$jsonSchema` 연산자로 그리고 `$match`로 집합 필터에서 필터링된 집합:

```
db.employees.aggregate(
    [{ $match: { 
        $jsonSchema: { 
            required: ["name", "employeeId"],  
            properties: {"salary" :{"bsonType": "double"}}
        }
       }
    }]
)
```

Amazon DocumentDB는 다음 출력을 반환합니다:

```
{ 
"_id" : ObjectId("64e5f8886218c620cf0e8f8a"),
 "name" : { "firstName" : "Carol", "lastName" : "Smith" },
"employeeId" : "c720a",
"salary" : 1000 
}
{
"_id" : ObjectId("64e5f91c6218c620cf0e8f8b"),
"name" : { "firstName" : "Emily", "lastName" : "Brown" },
"employeeId" : "c720b",
"age" : 25,
"salary" : 1050.2
}
{
"_id" : ObjectId("64e5f94e6218c620cf0e8f8c"),
"name" : { "firstName" : "William", "lastName" : "Taylor" },
"employeeId" : "c721a",
"age" : 24,
"salary" : 1400.5
}
{
"_id" : ObjectId("64e5f9786218c620cf0e8f8d"),
"name" : { "firstName" : "Jane", "lastName" : "Doe" },
"employeeId" : "c721a",
"salary" : 1300
}
```

### 기존 검증 규칙 보기
<a name="view-validation-rules"></a>

컬렉션의 기존 검증 규칙을 보려면 다음을 사용하세요:

```
db.runCommand({
    listCollections: 1, 
    filter: { name: 'employees' }
})
```

Amazon DocumentDB는 다음 출력을 반환합니다:

```
{
    "waitedMS" : NumberLong(0),
    "cursor" : {
        "firstBatch" : [
            {
                "name" : "employees",
                "type" : "collection",
                "options" : {
                    "autoIndexId" : true,
                    "capped" : false,
                    "validator" : {
                        "$jsonSchema" : {
                            "bsonType" : "object",
                            "title" : "employee validation",
                            "required" : [
                                "name",
                                "employeeId",
                                "salary"
                            ],
                            "properties" : {
                                "name" : {
                                    "bsonType" : "object",
                                    "properties" : {
                                        "firstName" : {
                                            "bsonType" : [
                                                "string"
                                            ]
                                        },
                                        "lastName" : {
                                            "bsonType" : [
                                                "string"
                                            ]
                                        }
                                    },
                                    "additionalProperties" : false
                                },
                                "employeeId" : {
                                    "bsonType" : "string",
                                    "description" : "Unique Identifier for employee"
                                },
                                "salary" : {
                                    "bsonType" : "double"
                                },
                                "age" : {
                                    "bsonType" : "number"
                                }
                            },
                            "additionalProperties" : true
                        }
                    },
                    "validationLevel" : "moderate",
                    "validationAction" : "error"
                },
                "info" : {
                    "readOnly" : false
                },
                "idIndex" : {
                    "v" : 2,
                    "key" : {
                        "_id" : 1
                    },
                    "name" : "_id_",
                    "ns" : "test.employees"
                }
            }
        ],
        "id" : NumberLong(0),
        "ns" : "test.$cmd.listCollections"
    },
    "ok" : 1,
    "operationTime" : Timestamp(1692788937, 1)
}
```

Amazon DocumentDB는 또한 `$out` 집계 단계에서 검증 규칙을 유지합니다.

## 지원되는 키워드
<a name="json-supported-keywords"></a>

`create`및 `collMod` 명령에서 지원되는 필드는 다음과 같습니다.
+ **`Validator`**— `$jsonSchem`a 연산자를 지원합니다.
+ **`ValidationLevel`**— `off``strict`, 및 `moderate` 값을 지원합니다.
+ **`ValidationAction`**— `error` 값을 지원합니다.

\$1jsonSchema 연산자는 다음 키워드를 지원합니다:
+ `additionalItems`
+ `additionalProperties`
+ `allOf`
+ `anyOf`
+ `bsonType`
+ `dependencies`
+ `description`
+ `enum`
+ `exclusiveMaximum`
+ `exclusiveMinimum`
+ `items`
+ `maximum`
+ `minimum`
+ `maxItems`
+ `minItems`
+ `maxLength`
+ `minLength`
+ `maxProperties`
+ `minProperties`
+ `multipleOf`
+ `not`
+ `oneOf`
+ `pattern`
+ `patternProperties`
+ `properties`
+ `required`
+ `title`
+ `type`
+ `uniqueItems`

## bypassDocumentValidation
<a name="json-schema-bypass"></a>

Amazon DocumentDB는 다음 명령 및 메서드에 대해 `bypassDocumentValidation`을 지원합니다.
+ `insert`
+ `update`
+ `findAndModify`
+ `aggregate` 명령 및 `db.collection.aggregate()` 메서드의 `$out` 단계

Amazon DocumentDB는 `bypassDocumentValidation`에 대해 다음 명령을 지원하지 않습니다.
+ `aggregate` 명령 및 `db.collection.aggregate()` 메서드의 `$merge`
+ `mapReduce` 명령 및 `db.collection.mapReduce()` 메서드
+ `applyOps` 명령

## 제한 사항
<a name="json-schema-limitations"></a>

`$jsonSchema`에는 다음과 같은 제한 사항이 적용됩니다.
+ Amazon DocumentDB는 작업이 검증 규칙에 실패하면 “문서 검증에 실패했습니다.”라는 오류를 반환합니다.
+ Amazon DocumentDB 탄력적 클러스터는 `$jsonSchema`를 지원하지 않습니다.