模式验证

在本页中

版本3.2中的新功能

MongoDB提供了在更新和插入期间执行模式验证的功能。

指定验证规则

验证规则基于每个集合。

要在创建新集合时指定验证规则,请使用db.createCollection()使用validator选项。

若要将文档验证添加到现有集合,请使用collMod带有 validator 选项的命令。

MongoDB还提供了以下相关选项:

  • validationLevel 选项,该选项确定MongoDB在更新期间对现有文档应用验证规则的严格程度,以及
  • validationAction 选项,该选项确定MongoDB是否应显示错误并拒绝违反验证规则的文档,或 warn 日志中的违反行为,但允许无效文档。

JSON模式

版本3.6中的新功能

从3.6版开始,MongoDB支持JSON模式验证。要指定JSON模式验证,请使用 $jsonSchema 操作validator表达式中的运算符。

注意

推荐使用JSON模式执行模式验证。

例如,以下示例使用JSON模式指定验证规则:

  1. db.createCollection("students", {
  2. validator: {
  3. $jsonSchema: {
  4. bsonType: "object",
  5. required: [ "name", "year", "major", "address" ],
  6. properties: {
  7. name: {
  8. bsonType: "string",
  9. description: "must be a string and is required"
  10. },
  11. year: {
  12. bsonType: "int",
  13. minimum: 2017,
  14. maximum: 3017,
  15. description: "must be an integer in [ 2017, 3017 ] and is required"
  16. },
  17. major: {
  18. enum: [ "Math", "English", "Computer Science", "History", null ],
  19. description: "can only be one of the enum values and is required"
  20. },
  21. gpa: {
  22. bsonType: [ "double" ],
  23. description: "must be a double if the field exists"
  24. },
  25. address: {
  26. bsonType: "object",
  27. required: [ "city" ],
  28. properties: {
  29. street: {
  30. bsonType: "string",
  31. description: "must be a string if the field exists"
  32. },
  33. city: {
  34. bsonType: "string",
  35. "description": "must be a string and is required"
  36. }
  37. }
  38. }
  39. }
  40. }
  41. }
  42. })

有关详细信息,请参见 $jsonSchema

其他查询表达式

除了使用$jsonSchema 操作查询运算符,MongoDB支持使用 其他查询运算符 查询选择器,除了$near$nearSphere$text,和 $where 运算符。

例如,以下示例使用查询表达式指定验证器规则:

  1. db.createCollection( "contacts",
  2. { validator: { $or:
  3. [
  4. { phone: { $type: "string" } },
  5. { email: { $regex: /@mongodb\.com$/ } },
  6. { status: { $in: [ "Unknown", "Incomplete" ] } }
  7. ]
  8. }
  9. } )

另请参见

查询运算符

行为

在更新和插入期间进行验证。将验证添加到集合时,现有文档在修改之前不会进行验证检查。

现有文档

validationLevel 选项确定MongoDB应用验证规则的操作:

  • 如果 validationLevelstrict(默认值),MongoDB会对所有插入和更新应用验证规则。
  • 如果 validationLevelmoderate,MongoDB将验证规则应用于已满足验证条件的现有文档的插入和更新。使用 moderate 级别时,不检查对不符合验证条件的现有文档的更新是否有效。

例如,使用以下文档创建 contacts 集合:

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

发出以下命令将验证器添加到 contacts 集合:

  1. db.runCommand( {
  2. collMod: "contacts",
  3. validator: { $jsonSchema: {
  4. bsonType: "object",
  5. required: [ "phone", "name" ],
  6. properties: {
  7. phone: {
  8. bsonType: "string",
  9. description: "must be a string and is required"
  10. },
  11. name: {
  12. bsonType: "string",
  13. description: "must be a string and is required"
  14. }
  15. }
  16. } },
  17. validationLevel: "moderate"
  18. } )

contacts 集合现在有一个使用 moderate 验证级别的验证器:

  • 如果试图更新 _id为1, MongoDB将应用验证规则,因为现有文档与条件匹配。
  • 相反,MongoDB不会对_id为2的文档应用验证规则,因为它不符合验证规则。

要完全禁用验证,可以将validationLevel设置为off

接受或拒绝无效文档

validationAction选项确定MongoDB如何处理违反验证规则的文档:

  • 如果validationActionerror (默认值),MongoDB将拒绝任何违反验证条件的插入或更新。
  • 如果validationActionwarn,MongoDB会记录任何冲突,但允许继续插入或更新。

例如,使用以下JSON模式验证器创建一个contacts2集合:

  1. db.createCollection( "contacts2", {
  2. validator: { $jsonSchema: {
  3. bsonType: "object",
  4. required: [ "phone" ],
  5. properties: {
  6. phone: {
  7. bsonType: "string",
  8. description: "must be a string and is required"
  9. },
  10. email: {
  11. bsonType : "string",
  12. pattern : "@mongodb\.com$",
  13. description: "must be a string and match the regular expression pattern"
  14. },
  15. status: {
  16. enum: [ "Unknown", "Incomplete" ],
  17. description: "can only be one of the enum values"
  18. }
  19. }
  20. } },
  21. validationAction: "warn"
  22. } )

使用warn validationAction,MongoDB会记录任何冲突,但允许继续插入或更新。

例如,以下插入操作违反了验证规则:

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

不过,由于validationAction 仅为warn ,MongoDB只记录验证冲突消息并允许操作继续:

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

限制

不能为adminlocalconfig 数据库中的集合指定验证器。

不能为 system.*集合指定验证器。

绕过文档验证

用户可以使用bypassDocumentValidation 选项绕过文档验证。

以下命令可以使用新选项bypassDocumentValidation跳过每个操作的验证:

对于已启用访问控制的部署,若要绕过文档验证,经过身份验证的用户必须具有bypassDocumentValidation行动。内置角色dbAdminrestore 提供此操作。

附加信息

另请参见

collMod, db.createCollection(), db.getCollectionInfos()

数据建模简介 数据建模概念

译者:张鹏

原文链接:https://docs.mongodb.com/manual/core/schema-validation/

参见

原文 - Schema Validation