模式验证(Schema Validation)


进入MongoDB中文手册(4.2版本)目录

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

1 指定验证规则

验证规则是基于每个集合的。
要在创建新集合时指定验证规则,请使用带有validator选项的db.createCollection()
要将文档验证添加到现有集合,请使用带有validator选项的collMod命令。
MongoDB还提供以下相关选项:

  • validationLevel 选项,该选项确定MongoDB在更新过程中对现有文档应用验证规则的严格程度,
  • validationAction选项,该选项确定MongoDB是应该报错还是拒绝违反验证规则的文档,或允许无效文档但在日志中记录违反验证规则的告警信息。

2 JSON模式(Schema)

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

注意
推荐使用JSON模式(Schema)进行模式(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"
                  }
               }
            }
         }
      }
   }
})

有关更多信息,请参见$jsonSchema

3 其他查询表达式

除了使用$jsonSchema查询运算符进行JSON模式验证,MongoDB的支持使用其他查询运算符进行验证,$near, $nearSphere,$text,和$where运算符除外。
例如,以下示例使用查询表达式指定验证器规则:

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

也可以看看

4 行为

验证在更新和插入期间进行。当您向集合中添加验证时,现有文档将不进行验证检查,直到进行修改。

4.1 现有文档

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

  • 如果validationLevel为strict(默认),则MongoDB将验证规则应用于所有插入和更新。
  • 如果validationLevel为moderate,则MongoDB将验证规则应用于已满足验证条件的现有文档的插入和更新。对于该moderate级别,不检查对不满足验证条件(criteria)的现有文档的更新的有效性。

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

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

发出以下命令以将验证器添加到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"
} )

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

  • 如果你试图用1更新文档中_id,MongoDB的会因为现有的文档匹配这个条件(criteria)而应用验证规则。
  • 相比之下,MongoDB中不会对_id为2的文档应用验证规则,因为它不符合验证规则。

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

4.2 接收或拒绝无效文档

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

  • 如果validationAction是error(默认),则MongoDB拒绝任何违反验证条件的插入或更新。
  • 如果validationAction为warn,则MongoDB会记录任何违反验证规则的情况,但允许进行插入或更新。

例如,使用以下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"
} )

validationAction使用warn,MongoDB会记录所有违反规则的情况,但允许进行插入或更新。
例如,以下插入操作违反了验证规则:

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

但是,由于validationAction只用了warn,因此MongoDB仅记录验证违反消息并允许操作继续进行:

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

5 限制

您不能在admin, local和config数据库中为集合指定验证器。
您不能为system.*集合指定验证器。

6 绕过文档验证

用户可以使用bypassDocumentValidation选项绕过文档验证 。
以下命令可以使用新的选项bypassDocumentValidation绕过每个操作的验证:

  • applyOps 命令
  • findAndModify命令与 db.collection.findAndModify()方法
  • mapReduce命令与 db.collection.mapReduce()方法
  • insert 命令
  • update 命令
  • 用于aggregate命令的$out和$merge阶段和 db.collection.aggregate()方法

对于已启用访问控制的部署,要绕过文档验证,已认证的用户必须使用bypassDocumentValidation。内置角色dbAdminrestore提供此操作。

7 其他信息

也可以看看

进入MongoDB中文手册(4.2版本)目录

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值