

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 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>

以下示例插入不符合上述架构验证规则的文档：在这个示例中，employeId 值不是字符串：

```
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 架构匹配的文档。这是一个可以作为顶级字段出现在筛选器文档中或可以配合查询运算符（例如 `$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` 运算符。
+ **`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`。