

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

# \$1jsonSchema
<a name="jsonSchema"></a>

4.0 版的新增内容。

弹性集群不支持。

Amazon DocumentDB 中的`$jsonSchema`运算符用于根据指定的 JSON 架构筛选文档。此运算符允许您查询与特定 JSON 架构匹配的文档，确保检索到的文档符合特定的结构和数据类型要求。

在创建集合时使用`$jsonSchema`评估查询运算符，可以验证插入到集合中的文档的架构。有关更多信息，请参阅[使用 JSON 架构验证](json-schema-validation.md)。

**参数**
+ `required`（数组）：指定文档中的必填字段。
+ `properties`（object）：定义文档中每个字段的数据类型和其他约束。

## 示例（MongoDB 外壳）
<a name="jsonSchema-examples"></a>

以下示例演示如何使用`$jsonSchema`运算符筛选`employees`集合，以仅检索具有`name`、`employeeId`和`age`字段且`employeeId`字段类型为的文档`string`。

**创建示例文档**

```
db.employees.insertMany([
  { "name": { "firstName": "Carol", "lastName": "Smith" }, "employeeId": "1" },
  { "name": { "firstName": "Emily", "lastName": "Brown" }, "employeeId": "2", "age": 25 },
  { "name": { "firstName": "William", "lastName": "Taylor" }, "employeeId": 3, "age": 24 },
  { "name": { "firstName": "Jane", "lastName": "Doe" }, "employeeId": "4" }
]);
```

**查询示例**

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

**输出**

```
{ "_id" : ObjectId("6908e8b61f77fc26b2ecd26f"), "name" : { "firstName" : "Emily", "lastName" : "Brown" }, "employeeId" : "2", "age" : 25 }
```

## 代码示例
<a name="jsonSchema-code"></a>

要查看使用该`$jsonSchema`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function filterByJsonSchema() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('employees');

  const result = await collection.aggregate([
    {
      $match: {
        $jsonSchema: {
          required: ['name', 'employeeId', 'age'],
          properties: { 'employeeId': { 'bsonType': 'string' } }
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

filterByJsonSchema();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def filter_by_json_schema():
  client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
  db = client['test']
  collection = db['employees']

  result = list(collection.aggregate([
    {
      '$match': {
        '$jsonSchema': {
          'required': ['name', 'employeeId', 'age'],
          'properties': {'employeeId': {'bsonType': 'string'}}
        }
      }
    }
  ]))

  print(result)
  client.close()

filter_by_json_schema()
```

------