$jsonSchema - Amazon DocumentDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

$jsonSchema

4.0 版的新增内容。

弹性集群不支持。

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

在创建集合时使用$jsonSchema评估查询运算符,可以验证插入到集合中的文档的架构。有关更多信息,请参阅使用 JSON 架构验证

参数

  • required(数组):指定文档中的必填字段。

  • properties(object):定义文档中每个字段的数据类型和其他约束。

示例(MongoDB 外壳)

以下示例演示如何使用$jsonSchema运算符筛选employees集合,以仅检索具有nameemployeeIdage字段且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 }

代码示例

要查看使用该$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()