On this page本页内容
MongoDB provides the capability to perform schema validation during updates and insertions.MongoDB提供了在更新和插入期间执行模式验证的功能。
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还提供以下相关选项:
validationLevel
validationAction
error
and reject documents that violate the validation rules or warn
about the violations in the log but allow invalid documents.error
并拒绝违反验证规则的文档,或在日志中warn
违规行为,但允许无效文档。MongoDB supports JSON Schema validation. MongoDB支持JSON模式验证。To specify JSON Schema validation, use the 要指定JSON模式验证,请在验证器表达式中使用$jsonSchema
operator in your validator
expression.$jsonSchema
运算符。
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
。
可以在BSON类型页面上找到bsonType
definitions can be found on the BSON Types page.bsonType
定义。
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" ] } } ] } } )
Validation occurs during updates and inserts. 在更新和插入期间进行验证。When you add validation to a collection, existing documents do not undergo validation checks until modification.向集合添加验证时,现有文档在修改之前不会进行验证检查。
To perform validation checks on existing documents, use the 要对现有文档执行验证检查,请使用validate
command or the db.collection.validate()
shell helper.validate
命令或db.collection.validate()
shell助手。
The validationLevel
option determines which operations MongoDB applies the validation rules:validationLevel
选项确定MongoDB应用验证规则的操作:
validationLevel
is strict
(the default), MongoDB applies validation rules to all inserts and updates.validationLevel
是strict
(默认),MongoDB将验证规则应用于所有插入和更新。validationLevel
is moderate
, MongoDB applies validation rules to inserts and to updates to existing documents that already fulfill the validation criteria. validationLevel
为moderate
,MongoDB将验证规则应用于已满足验证标准的现有文档的插入和更新。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.insertMany([ { "_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: "phone must be a string and is required" }, name: { bsonType: "string", description: "name must be a string and is required" } } } }, validationLevel: "moderate" } )
The contacts
collection now has a validator with the moderate
validationLevel:contacts
集合现在有一个具有moderate
验证级别的验证器:
_id: 1
, MongoDB would apply the new validation rules since the existing document matches the criteria._id:1
更新文档,MongoDB将应用新的验证规则,因为现有文档符合条件。_id: 2
as it does not meet the validation rules._id:2
文档的更新,因为它不符合验证规则。Starting in MongoDB version 5.0, the validator returns detailed error information when a validation condition isn't met. 从MongoDB 5.0版开始,当不满足验证条件时,验证器返回详细的错误信息。The error output is exhaustive - all errors are reported, not just the first one.错误输出是详尽的-报告所有错误,而不仅仅是第一个错误。
The error output is intended for human consumption. 错误输出旨在供人类使用。It may change in the future and should not be relied upon in scripts.它可能会在未来发生变化,不应在脚本中使用。
In the next example, neither of the updates is consistent with the validation rule we created above that requires 在下一个示例中,两个更新都不符合我们在上面创建的验证规则,该规则要求name
to be a string.name
为字符串。
db.contacts.updateOne( { _id: 1 }, { $set: { name: 10 } } ) db.contacts.updateOne( { _id: 2 }, { $set: { name: 20 } } )
The output below shows that the document with 下面的输出显示_id: 1
fails validation with a detailed explanation, as shown in the errInfo
object. _id:1
的文档验证失败,并给出了详细解释,如errInfo
对象所示。The update succeeds for the document with 对于_id: 2
since this document did not meet the initial criteria when validation was added._id:2
的文档,更新成功,因为添加验证时该文档不符合初始条件。
// _id: 1 MongoServerError: Document failed validation Additional information: { failingDocumentId: 1, details: { operatorName: '$jsonSchema', schemaRulesNotSatisfied: [ { operatorName: 'properties', propertiesNotSatisfied: [ { propertyName: 'name', description: 'name must be a string and is required', details: [ { operatorName: 'bsonType', specifiedAs: { bsonType: 'string' }, reason: 'type did not match', consideredValue: 10, consideredType: 'int' } ] } ] } ] } } // _id: 2 { acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 0, upsertedCount: 0 }
To disable validation entirely, you can set 要完全禁用验证,可以将validationLevel
to off
.validationLevel
设置为off
。
The validationAction
option determines how MongoDB handles documents that violate the validation rules:validationAction
选项确定MongoDB如何处理违反验证规则的文档:
validationAction
is error
(the default), MongoDB rejects any insert or update that violates the validation criteria.validationAction
为error
(默认),MongoDB将拒绝任何违反验证标准的插入或更新。validationAction
is warn
, MongoDB logs any violations but allows the insertion or update to proceed.validationAction
为warn
,MongoDB将记录任何违规行为,但允许继续插入或更新。For example, create a 例如,使用以下JSON模式验证器创建contacts2
collection with the following JSON Schema validator: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" } )
For example, the following insert operation violates the validation rule:例如,以下插入操作违反了验证规则:
db.contacts2.insertOne( { name: "Amanda", status: "Updated" } )
However, since the 但是,由于validationAction
is warn
, MongoDB only logs the validation violation message and allows the operation to proceed. Run the following command to view the MongoDB logs:validationAction
是warn
,MongoDB只记录验证违规消息并允许操作继续。运行以下命令查看MongoDB日志:
db.adminCommand( { getLog: "global" } )
Depending on collection usage, this command might return a lot of data. 根据集合使用情况,此命令可能会返回大量数据。The validation error (one long line in the log, reformatted here for readability) contains information like this:验证错误(日志中的一个长行,此处为可读性重新格式化)包含以下信息:
"{\"t\":{\"$date\":\"2021-01-20T15:59:57.305+00:00\"}, \"s\":\"W\", \"c\":\"STORAGE\", \"id\":20294, \"ctx\":\"conn1\", \"msg\":\"Document would fail validation\", \"attr\":{\"namespace\":\"test.contacts2\", \"document\":{\"_id\":{\"$oid\":\"6008537d42e0d23385568881\"}, \"name\":\"Amanda\", \"status\":\"Updated\"}, \"errInfo\":{\"failingDocumentId\":{\"$oid\":\"6008537d42e0d23385568881\"}, \"details\":{\"operatorName\":\"$jsonSchema\", \"schemaRulesNotSatisfied\":[ {\"operatorName\":\"properties\", \"propertiesNotSatisfied\":[ {\"propertyName\":\"status\", \"details\":[ {\"operatorName\":\"enum\", \"specifiedAs\":{\"enum\":[ \"Unknown\", \"Incomplete\"]}, \"reason\":\"value was not found in enum\", \"consideredValue\":\"Updated\"}]}]}, {\"operatorName\":\"required\", \"specifiedAs\":{\"required\":[\"phone\"]}, \"missingProperties\":[\"phone\"]}]}}}}"
Starting in MongoDB 5.1, when a document fails schema validation, MongoDB includes the validation 从MongoDB 5.1开始,当文档未能通过模式验证时,MongoDB会在错误响应中包含验证title
and description
in the error response. title
和description
。You can use these fields to provide a clearer explanation of the validation when the rules are not immediately clear, such as when using regular expressions.当规则不立即明确时,例如使用正则表达式时,您可以使用这些字段来更清楚地解释验证。
Consider a 考虑具有以下架构验证的users
collection with the following schema validation:users
集合:
db.runCommand( { collMod: "users", validator: { $jsonSchema: { bsonType: "object", title: "Email validation", properties: { email: { "bsonType": "string", "pattern": "^@mongodb\.com$", "description": "Email address must end with '@mongodb.com'" }, } } }, validationLevel: "moderate" } )
The pattern
field indicates that all email
fields must end with @mongodb.com
. pattern
字段表示所有email
字段必须以@mongodb.com
结尾。If you try to insert a document that does not match the pattern, MongoDB includes the validation 如果您尝试插入与模式不匹配的文档,MongoDB会在错误输出中包含验证title
and description
in the error output:title
和description
:
Input:
db.users.insertOne( { "name": "Amelia Morrison", "email": "a.morrison@nwsueicn.com" } )
Output:输出:
MongoServerError: Document failed validation Additional information: { failingDocumentId: ObjectId("614a10bab93bbd15dd2e2eb6"), details: { operatorName: '$jsonSchema', title: 'Email validation', schemaRulesNotSatisfied: [ { operatorName: 'properties', propertiesNotSatisfied: [ { propertyName: 'email', description: "Email address must end with '@mongodb.com'", details: [ { operatorName: 'pattern', specifiedAs: { pattern: '^@mongodb.com$' }, reason: 'regular expression did not match', consideredValue: 'a.morrison@nwsueicn.com' } ] } ] } ] } }
The validation error output is formatted differently in the legacy 在传统mongo
shell.mongo
shell中,验证错误输出的格式不同。
You cannot specify a validator for collections in the 不能为admin
, local
, and config
databases.admin
、local
和config
数据库中的集合指定验证器。
You cannot specify a validator for 不能为system.*
collections.system.*
集合指定验证器。
Users can bypass document validation using the 用户可以使用bypassDocumentValidation
option.bypassDocumentValidation
选项绕过文档验证。
The following commands can bypass validation per operation using the new option 以下命令可以使用新选项bypassDocumentValidation
:bypassDocumentValidation
绕过每个操作的验证:
applyOps
findAndModify
db.collection.findAndModify()
mapReduce
db.collection.mapReduce()
insert
update
$out
and $merge
stages for the aggregate
command and db.collection.aggregate()
methodaggregate
命令和db.collection.aggregate()
方法的$out
和$merge
阶段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.dbAdmin
和restore
提供了此操作。