You can specify how MongoDB handles documents that violate validation rules. When an operation would result in an invalid document, MongoDB can either:您可以指定MongoDB如何处理违反验证规则的文档。当一个操作会导致无效文档时,MongoDB可以:
Reject any insert or update that violates the validation criteria. This is the default behavior.拒绝任何违反验证条件的插入或更新。这是默认行为。Allow the operation to proceed, but record the violation in the MongoDB log.允许操作继续,但将违规记录在MongoDB日志中。
Rejecting invalid documents ensures that your schema stays consistent. However, in certain scenarios you may want to allow invalid documents, such as a data migration containing documents from before a schema was established.拒绝无效文档可确保架构保持一致。但是,在某些情况下,您可能希望允许无效文档,例如包含建立架构之前的文档的数据迁移。
Context上下文
Your schema's 模式的validationAction option determines how MongoDB handles invalid documents:validationAction选项决定了MongoDB如何处理无效文档:
| Behavior | |
|---|---|
error | |
warn | |
errorAndLog |
|
Note
If you use an 如果对集合使用errorAndLog validation action on a collection, MongoDB cannot downgrade until you drop the collection, or if you change the validation action for the collection to one supported in older versions. errorAndLog验证操作,则MongoDB无法降级,除非您删除该集合,或者将该集合的验证操作更改为旧版本支持的操作。To change the validation action on a collection, use the 要更改集合的验证操作,请使用collMod command.collMod命令。
Option 1: Reject Invalid Documents选项1:拒绝无效文档
The following procedure shows how to create a schema validation that rejects invalid documents.以下过程显示了如何创建拒绝无效文档的架构验证。
Create a collection with validationAction: "error".使用validationAction: "error"创建集合。
validationAction: "error".Create a 使用具有contacts collection with a JSON schema validator that has validationAction: "error":validationAction: "error"的JSON模式验证器创建contacts集合:
db.createCollection( "contacts", {
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 end with '@mongodb.com'"
}
}
} },
validationAction: "error"
} )
The error validationAction causes MongoDB to reject any invalid documents and prevent them from being inserted into the collection.error validationAction导致MongoDB拒绝任何无效文档,并阻止它们插入到集合中。
Attempt to insert an invalid document.尝试插入无效文档。
Attempt to insert the following document:尝试插入以下文档:
db.contacts.insertOne(
{ name: "Amanda", email: "amanda@xyz.com" }
)
The document violates the validation rule because:文档违反了验证规则,原因如下:
Theemailfield does not match the regular expression pattern.email字段与正则表达式模式不匹配。Theemailfield must end in@mongodb.com.email字段必须以@mongodb.com结尾。It is missing the required缺少必需的phonefield.phone字段。
The operation fails with the following error:操作失败,出现以下错误:
MongoServerError: Document failed validation
Additional information: {
failingDocumentId: ObjectId("6377cca4aac957f2b77ea955"),
details: {
operatorName: '$jsonSchema',
schemaRulesNotSatisfied: [
{
operatorName: 'properties',
propertiesNotSatisfied: [
{
propertyName: 'email',
description: "must be a string and end with '@mongodb.com'",
details: [
{
operatorName: 'pattern',
specifiedAs: { pattern: '@mongodb\\.com$' },
reason: 'regular expression did not match',
consideredValue: 'amanda@xyz.com'
}
]
}
]
},
{
operatorName: 'required',
specifiedAs: { required: [ 'phone' ] },
missingProperties: [ 'phone' ]
}
]
}
}Option 2: Allow Invalid Documents, but Record Them in the Log选项2:允许无效文档,但将其记录在日志中
The following procedure shows how to create a schema validation that allows invalid documents, but records invalid documents in the MongoDB log.以下过程显示了如何创建允许无效文档但在MongoDB日志中记录无效文档的模式验证。
Create a collection with validationAction: "warn".使用validationAction: "warn"创建集合。
validationAction: "warn".Create a 使用具有contacts2 collection with a JSON schema validator that has validationAction: "warn":validationAction: "warn"的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 end with '@mongodb.com'"
}
}
} },
validationAction: "warn"
} )
The warn validationAction allows invalid documents to be inserted into the collection. Invalid documents are recorded in the MongoDB log.warn validationAction允许将无效文档插入到集合中。MongoDB日志中记录了无效文档。
Attempt to insert an invalid document.尝试插入无效文档。
Attempt to insert the following document:尝试插入以下文档:
db.contacts2.insertOne(
{ name: "Amanda", email: "amanda@xyz.com" }
)
The document violates the validation rule because:文档违反了验证规则,原因如下:
Theemailfield does not match the regular expression pattern. Theemailfield must end in@mongodb.com.email字段与正则表达式模式不匹配。email字段必须以@mongodb.com结尾。It is missing the required缺少必需的phonefield.phone字段。
Check the logs for the invalid document.检查日志中是否有无效文档。
To view the MongoDB logs in a readable format, run the following command:要以可读格式查看MongoDB日志,请运行以下命令:
db.adminCommand(
{ getLog:'global'} ).log.forEach(x => { print(x) }
)
The MongoDB log includes an entry similar to the following object:MongoDB日志包含一个类似于以下对象的条目:
{
"t": {
"$date": "2022-11-18T13:30:43.607-05:00"
},
"s": "W",
"c": "STORAGE",
"id": 20294,
"ctx": "conn2",
"msg": "Document would fail validation",
"attr": {
"namespace": "test.contacts2",
"document": {
"_id": {
"$oid": "6377cf53d59841355cac1cd0"
},
"name": "Amanda",
"email": "amanda@xyz.com"
},
"errInfo": {
"failingDocumentId": {
"$oid": "6377cf53d59841355cac1cd0"
},
"details": {
"operatorName": "$jsonSchema",
"schemaRulesNotSatisfied": [{
"operatorName": "properties",
"propertiesNotSatisfied": [{
"propertyName": "email",
"description": "must be a string and end with '@mongodb.com'",
"details": [{
"operatorName": "pattern",
"specifiedAs": {
"pattern": "@mongodb\\.com$"
},
"reason": "regular expression did not match",
"consideredValue": "amanda@xyz.com"
}]
}]
}, {
"operatorName": "required",
"specifiedAs": {
"required": ["phone"]
},
"missingProperties": ["phone"]
}]
}
}
}
}