

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 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`修改器：
+ **strict**：在所有插入和更新上套用驗證規則。
+ **中等**：將驗證規則套用至現有的有效文件。在更新期間，不會檢查現有的無效文件。

在下列範例中，更新名為「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 結構描述的文件。這是頂層運算子，可以做為頂層欄位出現在篩選文件中，或與查詢運算子搭配使用`$or`，例如 `$and`、 和 `$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 }
```

在彙總篩選條件`$match`中，使用`$jsonSchema`運算子和 篩選的集合：

```
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`運算子。
+ **`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`
+ `$out` `aggregate`命令和`db.collection.aggregate()`方法中的階段

Amazon DocumentDB 不支援 的下列命令`bypassDocumentValidation`：
+ `$merge` 在`aggregate`命令中和`db.collection.aggregate()`方法中
+ `mapReduce` 命令和`db.collection.mapReduce()`方法
+ `applyOps` 命令

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

下列限制適用於`$jsonSchema`驗證：
+ 當 操作失敗驗證規則時，Amazon DocumentDB 會傳回錯誤「文件驗證失敗」。
+ Amazon DocumentDB 彈性叢集不支援 `$jsonSchema`。