$jsonSchema

On this page本页内容

Definition定义

$jsonSchema

The $jsonSchema operator matches documents that satisfy the specified JSON Schema.$jsonSchema运算符匹配满足指定JSON模式的文档。

The $jsonSchema operator expression has the following syntax:$jsonSchema运算符表达式具有以下语法:

{ $jsonSchema: <JSON Schema object> }

Where the JSON Schema object is formatted according to draft 4 of the JSON Schema standard.其中JSON模式对象根据JSON模式标准的草案4格式化。

{ <keyword1>: <value1>, ... }

For example:例如:

{
  $jsonSchema: {
     required: [ "name", "major", "gpa", "address" ],
     properties: {
        name: {
           bsonType: "string",
           description: "must be a string and is required"
        },
        address: {
           bsonType: "object",
           required: [ "zipcode" ],
           properties: {
               "street": { bsonType: "string" },
               "zipcode": { bsonType: "string" }
           }
        }
     }
  }
}

For a list of keywords supported by MongoDB, see Available Keywords.有关MongoDB支持的关键字列表,请参阅可用关键字

Note注意

MongoDB supports draft 4 of JSON Schema, including core specification and validation specification, with some differences. MongoDB支持JSON模式草案4,包括核心规范验证规范,但存在一些差异。See Extensions and Omissions for details.有关详细信息,请参阅扩展省略

For more information about JSON Schema, see the official website.有关JSON模式的更多信息,请参阅官方网站

Behavior行为

Feature Compatibility功能兼容性

The featureCompatibilityVersion must be set to "3.6" or higher in order to use $jsonSchema.featureCompatibilityVersion必须设置为"3.6"或更高,才能使用$jsonSchema

Document Validator文档验证器

You can use $jsonSchema in a document validator to enforce the specified schema on insert and update operations:您可以在文档验证器中使用$jsonSchema在插入和更新操作中强制执行指定的模式:

db.createCollection( <collection>, { validator: { $jsonSchema: <schema> } } )
db.runCommand( { collMod: <collection>, validator:{ $jsonSchema: <schema> } } )

Query Conditions查询条件

You can use $jsonSchema in query conditions for read and write operations to find documents in the collection that satisfy the specified schema:您可以在读写操作的查询条件中使用$jsonSchema来查找集合中满足指定架构的文档:

db.collection.find( { $jsonSchema: <schema> } )
db.collection.aggregate( [ { $match: { $jsonSchema: <schema> } } ] )
db.collection.updateMany( { $jsonSchema: <schema> }, <update> )
db.collection.deleteOne( { $jsonSchema: <schema> } )

To find documents in the collection that do not satisfy the specified schema, use the $jsonSchema expression in a $nor expression. 要查找集合中满足指定架构的文档,请在$nor表达式中使用$jsonSchema表达式。For example:例如:

db.collection.find( { $nor: [ { $jsonSchema: <schema> } ] } )
db.collection.aggregate( [ { $match: { $nor: [ { $jsonSchema: <schema> } ] } }, ... ] )
db.collection.updateMany( { $nor: [ { $jsonSchema: <schema> } ] }, <update> )
db.collection.deleteOne( { $nor: [ { $jsonSchema: <schema> } ] } )

Examples示例

Schema Validation模式验证

The following db.createCollection() method creates a collection named students and uses the $jsonSchema operator to set schema validation rules:以下db.createCollection()方法创建名为students的集合,并使用$jsonSchema运算符设置架构验证规则:

db.createCollection("students", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         required: [ "name", "year", "major", "address" ],
         properties: {
            name: {
               bsonType: "string",
               description: "must be a string and is required"
            },
            year: {
               bsonType: "int",
               minimum: 2017,
               maximum: 3017,
               description: "must be an integer in [ 2017, 3017 ] and is required"
            },
            major: {
               enum: [ "Math", "English", "Computer Science", "History", null ],
               description: "can only be one of the enum values and is required"
            },
            gpa: {
               bsonType: [ "double" ],
               description: "must be a double if the field exists"
            },
            address: {
               bsonType: "object",
               required: [ "city" ],
               properties: {
                  street: {
                     bsonType: "string",
                     description: "must be a string if the field exists"
                  },
                  city: {
                     bsonType: "string",
                     "description": "must be a string and is required"
                  }
               }
            }
         }
      }
   }
} )

Given the created validator for the collection, the following insert operation will fail because gpa is an integer when the validator requires a double.给定为集合创建的validator,以下插入操作将失败,因为当validator需要double时,gpa是整数。

db.students.insertOne( {
   name: "Alice",
   year: Int32( 2019 ),
   major: "History",
   gpa: Int32( 3 ),
   address: {
      city: "NYC",
      street: "33rd Street"
   }
} )

The operation returns the following error:操作返回以下错误:

MongoServerError: Document failed validation
Additional information: {
  failingDocumentId: ObjectId("61aa577f666a50a8fccd7ec2"),
  details: {
    operatorName: '$jsonSchema',
    schemaRulesNotSatisfied: [
      {
        operatorName: 'properties',
        propertiesNotSatisfied: [
          {
            propertyName: 'gpa',
            description: 'must be a double if the field exists',
            details: [ [Object] ]
          }
        ]
      }
    ]
  }
}

After changing the gpa to a double, the insert succeeds:gpa更改为double后,插入成功:

db.students.insertOne( {
   name: "Alice",
   year: NumberInt(2019),
   major: "History",
   gpa: Double(3.0),
   address: {
      city: "NYC",
      street: "33rd Street"
   }
} )

Query Conditions查询条件

You can use $jsonSchema in query conditions for read and write operations to find documents in the collection that satisfy the specified schema.您可以在读写操作的查询条件中使用$jsonSchema来查找集合中满足指定模式的文档。

For example, create a sample collection inventory with the following documents:例如,使用以下文档创建样本集合inventory

db.inventory.insertMany( [
   { item: "journal", qty: NumberInt(25), size: { h: 14, w: 21, uom: "cm" }, instock: true },
   { item: "notebook", qty: NumberInt(50), size: { h: 8.5, w: 11, uom: "in" }, instock: true },
   { item: "paper", qty: NumberInt(100), size: { h: 8.5, w: 11, uom: "in" }, instock: 1 },
   { item: "planner", qty: NumberInt(75), size: { h: 22.85, w: 30, uom: "cm" }, instock: 1 },
   { item: "postcard", qty: NumberInt(45), size: { h: 10, w: 15.25, uom: "cm" }, instock: true },
   { item: "apple", qty: NumberInt(45), status: "A", instock: true },
   { item: "pears", qty: NumberInt(50), status: "A", instock: true }
] )

Next, define the following sample schema object:接下来,定义以下示例架构对象:

let myschema =  {
      required: [ "item", "qty", "instock" ],
      properties: {
         item: { bsonType: "string" },
         qty: { bsonType: "int" },
         size: {
            bsonType: "object",
            required: [ "uom" ],
            properties: {
               uom: { bsonType: "string" },
               h: { bsonType: "double" },
               w: { bsonType: "double" }
            }
          },
          instock: { bsonType: "bool" }
      }
 }

You can use $jsonSchema to find all documents in the collection that satisfy the schema:您可以使用$jsonSchema查找集合中满足架构的所有文档:

db.inventory.find( { $jsonSchema: myschema } )
db.inventory.aggregate( [ { $match: { $jsonSchema: myschema } } ] )

You can use $jsonSchema with the $nor to find all documents that do not satisfy the schema:您可以将$jsonSchema$nor一起使用,以查找所有不满足架构的文档:

db.inventory.find( { $nor: [ { $jsonSchema: myschema } ] } )

Or, you can update all documents that do not satisfy the schema:或者,您可以更新所有不满足架构的文档:

db.inventory.updateMany( { $nor: [ { $jsonSchema: myschema } ] }, { $set: { isValid: false } } )

Or, you can delete all documents that do not satisfy the schema:或者,您可以删除所有不满足架构的文档:

db.inventory.deleteMany( { $nor: [ { $jsonSchema: myschema } ] } )

JSON Schema

MongoDB supports draft 4 of JSON Schema, including core specification and validation specification, with some differences. MongoDB支持JSON模式草案4,包括核心规范验证规范,但存在一些差异。See Extensions and Omissions for details.有关详细信息,请参阅扩展省略

For more information about JSON Schema, see the official website.有关JSON模式的更多信息,请参阅官方网站

Available Keywords可用关键字

Note注意

MongoDB implements a subset of keywords available in JSON Schema. MongoDB实现了JSON模式中可用的关键字子集。For a complete list of omissions, see Omissions.有关遗漏的完整列表,请参阅遗漏

KeywordType类型Definition定义Behavior行为
bsonTypeall typesstring alias or array of string aliasesAccepts same string aliases used for the $type operator接受用于$type运算符的相同字符串别名
enumall typesarray of valuesEnumerates all possible values of the field枚举字段的所有可能值
typeall typesstring or array of unique strings

Enumerates the possible JSON types of the field. 枚举字段的可能JSON类型。Available types are "object", "array", "number", "boolean", "string", and "null".可用类型有"object""array""number""boolean""string""null"

MongoDB's implementation of the JSON Schema does not support the "integer" type. Use the bsonType keyword and the "int" or "long" types instead.MongoDB对JSON模式的实现不支持“整数”类型。请改用bsonType关键字和“int”或“long”类型。

allOfall typesarray of JSON Schema objectsField must match all specified schemas字段必须匹配所有指定的架构
anyOfall typesarray of JSON Schema objectsField must match at least one of the specified schemas字段必须至少与一个指定的架构匹配
oneOfall typesarray of JSON Schema objectsField must match exactly one of the specified schemas字段必须完全匹配指定的架构之一
notall typesa JSON Schema objectField must not match the schema字段不能与架构匹配
multipleOfnumbersnumberField must be a multiple of this value字段必须是此值的倍数
maximumnumbersnumberIndicates the maximum value of the field指示字段的最大值
exclusiveMaximumnumbersbooleanIf true and field is a number, maximum is an exclusive maximum. 如果为true且字段为数字,则maximum为排除式的最大值。Otherwise, it is an inclusive maximum.否则,它是包含式的最大值。
minimumnumbersnumberIndicates the minimum value of the field指示字段的最小值
exclusiveMinimumnumbersbooleanIf true, minimum is an exclusive minimum. 如果为真,则minimum为排除式的最小值。Otherwise, it is an inclusive minimum.否则,它是包含式的最小值。
maxLengthstringsintegerIndicates the maximum length of the field指示字段的最大长度
minLengthstringsintegerIndicates the minimum length of the field指示字段的最小长度
patternstringsstring containing a regexField must match the regular expression字段必须与正则表达式匹配
maxPropertiesobjectsintegerIndicates the field's maximum number of properties指示字段的最大属性数
minPropertiesobjectsintegerIndicates the field's minimum number of properties指示字段的最小属性数
requiredobjectsarray of unique stringsObject's property set must contain all the specified elements in the array对象的属性集必须包含数组中的所有指定元素
additionalPropertiesobjectsboolean or object

If true, additional fields are allowed. 如果为true,则允许其他字段。If false, they are not. 如果为false,则不是。If a valid JSON Schema object is specified, additional fields must validate against the schema.如果指定了有效的JSON模式对象,则必须根据模式验证其他字段。

Defaults to true.默认为true

propertiesobjectsobjectA valid JSON Schema where each value is also a valid JSON Schema object一个有效的JSON模式,其中每个值也是一个有效JSON模式对象
patternPropertiesobjectsobjectIn addition to properties requirements, each property name of this object must be a valid regular expression除了properties要求外,此对象的每个属性名必须是有效的正则表达式
dependenciesobjectsobjectDescribes field or schema dependencies描述字段或架构依赖关系
additionalItemsarraysboolean or objectIf an object, must be a valid JSON Schema如果是对象,则必须是有效的JSON模式
itemsarraysobject or arrayMust be either a valid JSON Schema, or an array of valid JSON Schemas必须是有效的JSON架构或有效JSON架构数组
maxItemsarraysintegerIndicates the maximum length of array指示数组的最大长度
minItemsarraysintegerIndicates the minimum length of array指示数组的最小长度
uniqueItemsarraysbooleanIf true, each item in the array must be unique. 如果为true,则数组中的每个项都必须是唯一的。Otherwise, no uniqueness constraint is enforced.否则,不强制执行唯一性约束。
titleN/AstringA descriptive title string with no effect.无效的描述性标题字符串。
descriptionN/AstringA string that describes the schema and has no effect on validation. 描述架构且对验证没有影响的字符串。Starting in MongoDB 5.1, if the description field is specified, MongoDB includes the description in the error output when a document fails validation.从MongoDB 5.1开始,如果指定了description字段,则当文档验证失败时,MongoDB会在错误输出中包含description

Extensions扩展

MongoDB's implementation of JSON Schema includes the addition of the bsonType keyword, which allows you to use all BSON types in the $jsonSchema operator. MongoDB对JSON模式的实现包括添加bsonType关键字,这允许您在$jsonSchema运算符中使用所有BSON类型。bsonType accepts the same string aliases used for the $type operator.接受用于$type运算符的相同字符串别名。

Omissions遗漏

The following are not supported in MongoDB's implementation of JSON Schema:MongoDB对JSON模式的实现不支持以下内容:

  • Hypertext definitions in draft 4 of the JSON Schema spec.JSON模式规范草案4中的超文本定义
  • The keywords:关键词:

    • $ref
    • $schema
    • default
    • definitions
    • format
    • id
  • The integer type. integer类型。You must use the BSON type int or long with the bsonType keyword.必须将BSON类型intlongbsonType关键字一起使用。
  • Hypermedia and linking properties of JSON Schema, including the use of JSON References and JSON Pointers.JSON模式的超媒体和链接属性,包括JSON引用和JSON游标的使用。
  • Unknown keywords.未知关键字。
←  $expr$mod →