

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# Menggunakan validasi skema JSON
<a name="json-schema-validation"></a>

Menggunakan operator kueri `$jsonSchema` evaluasi, Anda dapat memvalidasi dokumen yang dimasukkan ke dalam koleksi Anda.

**Topics**
+ [Membuat dan menggunakan validasi skema JSON](#get-started-with-validation)
+ [Kata kunci yang didukung](#json-supported-keywords)
+ [bypassDocumentValidation](#json-schema-bypass)
+ [Batasan](#json-schema-limitations)

## Membuat dan menggunakan validasi skema JSON
<a name="get-started-with-validation"></a>

### Membuat koleksi dengan validasi skema
<a name="create-collection-with-validation"></a>

Anda dapat membuat koleksi dengan aturan `createCollection` operasi dan validasi. Aturan validasi ini diterapkan selama penyisipan atau pembaruan dokumen Amazon DocumentDB. Contoh kode berikut menunjukkan aturan validasi untuk koleksi karyawan:

```
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"
} )
```

### Memasukkan dokumen yang valid
<a name="insert-valid-document"></a>

Contoh berikut menyisipkan dokumen yang sesuai dengan aturan validasi skema di atas:

```
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})
```

### Memasukkan dokumen yang tidak valid
<a name="insert-invalid-document"></a>

Contoh berikut menyisipkan dokumen yang tidak sesuai dengan aturan validasi skema di atas. Dalam contoh ini, nilai EmployeeId bukan string:

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

Contoh ini menunjukkan sintaks yang salah dalam dokumen.

### Memodifikasi koleksi
<a name="modify-collection"></a>

`collMod`Perintah ini digunakan untuk menambah atau memodifikasi aturan validasi koleksi yang ada. Contoh berikut menambahkan bidang gaji ke daftar bidang wajib:

```
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 
      }
   }
} )
```

### Mengatasi dokumen yang ditambahkan sebelum aturan validasi diubah
<a name="pre-validation-docs"></a>

Untuk menangani dokumen yang ditambahkan ke koleksi Anda sebelum aturan validasi diubah, gunakan `validationLevel` pengubah berikut:
+ **ketat**: Menerapkan aturan validasi pada semua sisipan dan pembaruan.
+ **moderat**: Menerapkan aturan validasi ke dokumen valid yang ada. Selama pembaruan, dokumen tidak valid yang ada tidak diperiksa.

Dalam contoh berikut, setelah memperbarui aturan validasi pada koleksi bernama “karyawan”, bidang gaji diperlukan. Memperbarui dokumen berikut akan gagal:

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

Amazon DocumentDB mengembalikan output berikut:

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

Memperbarui tingkat validasi `moderate` akan memungkinkan dokumen di atas diperbarui dengan sukses:

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

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

Amazon DocumentDB mengembalikan output berikut:

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

### Mengambil dokumen dengan \$1JSONSchema
<a name="json-retrieve-docs"></a>

`$jsonSchema`Operator dapat digunakan sebagai filter untuk menanyakan dokumen yang cocok dengan skema JSON. Ini adalah operator tingkat atas yang dapat hadir dalam dokumen filter sebagai bidang tingkat atas atau digunakan dengan operator kueri seperti`$and`,`$or`, dan`$nor`. Contoh berikut menunjukkan penggunaan \$1JSONSchema sebagai filter individual dan dengan operator filter lainnya:

Dokumen dimasukkan ke dalam koleksi “karyawan”:

```
{ "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 }
```

Koleksi disaring dengan `$jsonSchema` operator saja:

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

Amazon DocumentDB mengembalikan output berikut:

```
{ "_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 }
```

Koleksi disaring dengan `$jsonSchema` operator dan operator lain:

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

Amazon DocumentDB mengembalikan output berikut:

```
{ "_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 }
```

Koleksi disaring dengan `$jsonSchema` operator dan dengan `$match` dalam filter agregat:

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

Amazon DocumentDB mengembalikan output berikut:

```
{ 
"_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
}
```

### Melihat aturan validasi yang ada
<a name="view-validation-rules"></a>

Untuk melihat aturan validasi yang ada pada koleksi, gunakan:

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

Amazon DocumentDB mengembalikan output berikut:

```
{
    "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 juga mempertahankan aturan validasi dalam tahap agregasi. `$out`

## Kata kunci yang didukung
<a name="json-supported-keywords"></a>

Bidang berikut didukung dalam `collMod` perintah `create` dan:
+ **`Validator`**— `$jsonSchem` Mendukung operator.
+ **`ValidationLevel`**— Mendukung`off`,`strict`, dan `moderate` nilai-nilai.
+ **`ValidationAction`**— Mendukung `error` nilai.

Operator \$1JSONSchema mendukung kata kunci berikut:
+ `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` mendukung perintah dan metode berikut:
+ `insert`
+ `update`
+ `findAndModify`
+ `$out`tahap dalam `aggregate` perintah dan `db.collection.aggregate()` metode

Amazon DocumentDB tidak mendukung perintah berikut untuk: `bypassDocumentValidation` 
+ `$merge`dalam `aggregate` perintah dan dalam `db.collection.aggregate()` metode
+ `mapReduce`perintah dan `db.collection.mapReduce()` metode
+ Perintah `applyOps`

## Batasan
<a name="json-schema-limitations"></a>

Batasan berikut berlaku untuk `$jsonSchema` validasi:
+ Amazon DocumentDB mengembalikan kesalahan “Dokumen gagal validasi” ketika operasi gagal dalam aturan validasi.
+ Cluster elastis Amazon DocumentDB tidak mendukung. `$jsonSchema`