Choose How to Handle Invalid Documents选择如何处理无效文档
On this page本页内容
You can specify how MongoDB handles documents that violate violation rules. 您可以指定MongoDB如何处理违反违规规则的文档。When an operation would result in an invalid document, MongoDB can either:当操作将导致无效文档时,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如何处理无效文档:
error | (Default) |
---|---|
warn |
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.validationAction
为error
导致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:该文档违反了验证规则,因为:
Theemail
field does not match the regular expression pattern.email
字段与正则表达式模式不匹配。Theemail
field must end in@mongodb.com
.email
字段必须以@mongodb.com
结尾。It is missing the required它缺少必需的phone
field.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. validationAction
为warn
允许将无效文档插入集合中。Invalid documents are recorded in the MongoDB log.无效文档记录在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:该文档违反了验证规则,因为:
Theemail
field does not match the regular expression pattern.email
字段与正则表达式模式不匹配。Theemail
field must end in@mongodb.com
.email
字段必须以@mongodb.com
结尾。It is missing the required它缺少必需的phone
field.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"]
}]
}
}
}
}