我是靠谱客的博主 沉默香水,这篇文章主要介绍Mongo Document Validation翻译自官方文档,现在分享给大家,希望可以做个参考。

翻译自官方文档
Document Validation(文档格式验证)
New in version 3.2. (3.2新特性)
默认情况下一个集合的文档可以有不同的格式,即一个集合中的文档不需要有相同的字段名并且字段的数据类型可以各不相同。(集合类似于关系数据库中的表,文档类似于表中的一行数据。)
从3.2开始我们可以规定集合中文档的格式(Document Validation)。

Schema Validation
Document Validation是对于一个集合来制定的(想说明不是针对整个数据库而是一个集合)。
指定验证格式:

  • 在创建新集合的时候使用 db.createCollection()命令在validator选项中加上验证规则来指定集合的文档格式。(指定完文档格式之后,在插入和更新文档的时候mongodb会验证文档是否符合格式规则)
  • 给一个已有的集合添加验证规则使用collMod命令

mongodb也支持下列相关选项:

  • 验证级别选项(validationLevel option):决定了mongodb对文档数据更新时执行格式验证的级别。
  • 验证行为选项(validationAction option):可以定义mongodb对于不符合验证规则的文档数据是采取报错并且拒绝文档更新,还是只在日志中记录一个warning并接受这样的文档更新。

JSON Schema

从3.6版本开始,mongo支持json格式的验证规则。即可以在验证规则中使用$jsonSchema来表达验证规则(用json形式来表达验证规则)。
例子:创建一个集合students,对集合中文档的字段限定规则:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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" } } } } } } })

最后

以上就是沉默香水最近收集整理的关于Mongo Document Validation翻译自官方文档的全部内容,更多相关Mongo内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(65)

评论列表共有 0 条评论

立即
投稿
返回
顶部