Schema Validation架构验证

On this page本页内容

New in version 3.2.版本3.2中的新功能。

MongoDB provides the capability to perform schema validation during updates and insertions.MongoDB提供了在更新和插入期间执行模式验证的功能。

Specify Validation Rules指定验证规则

Validation rules are on a per-collection basis.验证规则基于每个集合。

To specify validation rules when creating a new collection, use db.createCollection() with the validator option.要在创建新集合时指定验证规则,请使用db.createCollection()配合validator选项。

To add document validation to an existing collection, use collMod command with the validator option.要向现有集合添加文档验证,请使用collMod命令和validator选项。

MongoDB also provides the following related options:MongoDB还提供以下相关选项:

JSON Schema架构

New in version 3.6.版本3.6中的新功能。

Starting in version 3.6, MongoDB supports JSON Schema validation.从版本3.6开始,MongoDB支持JSON架构验证。To specify JSON Schema validation, use the $jsonSchema operator in your validator expression.要指定JSON架构验证,请在validator表达式中使用$jsonSchema运算符。

Note

JSON Schema is the recommended means of performing schema validation.JSON架构是执行模式验证的推荐方法。

For example, the following example specifies validation rules using JSON schema:例如,以下示例使用JSON架构指定验证规则:

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"
                  }
               }
            }
         }
      }
   }
})

For more information, see $jsonSchema.有关更多信息,请参阅$jsonSchema

Other Query Expressions其他查询表达式

In addition to JSON Schema validation that uses the $jsonSchema query operator, MongoDB supports validation with other query operators, with the exception of:除了使用$jsonSchema查询运算符的JSON架构验证之外,MongoDB还支持对其他查询运算符进行验证,但以下情况除外:

For example, the following example specifies validator rules using the query expression:例如,以下示例使用查询表达式指定验证程序规则:

db.createCollection( "contacts",
   { validator: { $or:
      [
         { phone: { $type: "string" } },
         { email: { $regex: /@mongodb\.com$/ } },
         { status: { $in: [ "Unknown", "Incomplete" ] } }
      ]
   }
} )

See also另请参阅

query operators查询运算符

Behavior行为

Validation occurs during updates and inserts.在更新和插入期间进行验证。When you add validation to a collection, existing documents do not undergo validation checks until modification.向集合添加验证时,现有文档在修改之前不会进行验证检查。

Existing Documents现有文件

The validationLevel option determines which operations MongoDB applies the validation rules:validationLevel选项确定MongoDB应用验证规则的操作:

  • If the validationLevel is strict (the default), MongoDB applies validation rules to all inserts and updates.如果validationLevelstrict(默认值),MongoDB将验证规则应用于所有插入和更新。
  • If the validationLevel is moderate, MongoDB applies validation rules to inserts and to updates to existing documents that already fulfill the validation criteria.如果validationLevelmoderate,MongoDB会将验证规则应用于已满足验证标准的现有文档的插入和更新。With the moderate level, updates to existing documents that do not fulfill the validation criteria are not checked for validity.对于moderate级别,对不符合验证标准的现有文档的更新不会进行有效性检查。

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

db.contacts.insert([
   { "_id": 1, "name": "Anne", "phone": "+1 555 123 456", "city": "London", "status": "Complete" },
   { "_id": 2, "name": "Ivan", "city": "Vancouver" }
])

Issue the following command to add a validator to the contacts collection:发出以下命令将验证程序添加到contacts集合:

db.runCommand( {
   collMod: "contacts",
   validator: { $jsonSchema: {
      bsonType: "object",
      required: [ "phone", "name" ],
      properties: {
         phone: {
            bsonType: "string",
            description: "must be a string and is required"
         },
         name: {
            bsonType: "string",
            description: "must be a string and is required"
         }
      }
   } },
   validationLevel: "moderate"
} )

The contacts collection now has a validator with the moderate validationLevel:contacts集合现在有一个具有moderate校验级别的验证器:

  • If you attempted to update the document with _id of 1, MongoDB would apply the validation rules since the existing document matches the criteria.如果您试图更新_id1的文档,MongoDB将应用验证规则,因为现有文档符合条件。
  • In contrast, MongoDB will not apply validation rules to updates to the document with _id of 2 as it does not meet the validation rules.相反,MongoDB不会将验证规则应用于_id2的文档的更新,因为它不符合验证规则。

To disable validation entirely, you can set validationLevel to off.要完全禁用验证,可以将validationLevel设置为off

Accept or Reject Invalid Documents接受或拒绝无效文件

The validationAction option determines how MongoDB handles documents that violate the validation rules:validationAction选项确定MongoDB如何处理违反验证规则的文档:

  • If the validationAction is error (the default), MongoDB rejects any insert or update that violates the validation criteria.如果validationActionerror(默认值),MongoDB将拒绝任何违反验证条件的插入或更新。
  • If the validationAction is warn, MongoDB logs any violations but allows the insertion or update to proceed.如果validationActionwarn,MongoDB将记录任何违规行为,但允许继续插入或更新。

For example, create a contacts2 collection with the following JSON Schema validator:例如,使用以下JSON架构验证程序创建contacts2集合:

db.createCollection( "contacts2", {
   validator: { $jsonSchema: {
      bsonType: "object",
      required: [ "phone" ],
      properties: {
         phone: {
            bsonType: "string",
            description: "must be a string and is required"
         },
         email: {
            bsonType : "string",
            pattern : "@mongodb\.com$",
            description: "must be a string and match the regular expression pattern"
         },
         status: {
            enum: [ "Unknown", "Incomplete" ],
            description: "can only be one of the enum values"
         }
      }
   } },
   validationAction: "warn"
} )

With the warn validationAction, MongoDB logs any violations but allows the insertion or update to proceed.使用warn validationAction,MongoDB会记录任何违规行为,但允许继续插入或更新。

For example, the following insert operation violates the validation rule:例如,以下插入操作违反了验证规则:

db.contacts2.insert( { name: "Amanda", status: "Updated" } )

However, since the validationAction is warn only, MongoDB only logs the validation violation message and allows the operation to proceed:但是,由于validationAction是只是warn,MongoDB只记录验证冲突消息并允许操作继续:

2017-12-01T12:31:23.738-05:00 W STORAGE  [conn1] Document would fail validation collection: example.contacts2 doc: { _id: ObjectId('5a2191ebacbbfc2bdc4dcffc'), name: "Amanda", status: "Updated" }

Restrictions限制

You cannot specify a validator for collections in the admin, local, and config databases.不能为adminlocalconfig数据库中的集合指定验证程序。

You cannot specify a validator for system.* collections.不能为system.*集合指定验证程序。

Bypass Document Validation绕过文档验证

Users can bypass document validation using the bypassDocumentValidation option.用户可以使用bypassDocumentValidation选项绕过文档验证。

The following commands can bypass validation per operation using the new option bypassDocumentValidation:以下命令可以使用新选项bypassDocumentValidation绕过每个操作的验证:

For deployments that have enabled access control, to bypass document validation, the authenticated user must have bypassDocumentValidation action.对于启用了访问控制的部署,要绕过文档验证,经过身份验证的用户必须具有bypassDocumentValidation操作。The built-in roles dbAdmin and restore provide this action.内置角色dbAdminrestore提供此操作。

Additional Information附加信息