Docs HomeMongoDB Manual

Choose How to Handle Invalid Documents选择如何处理无效文档

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如何处理无效文档:

Validation Action验证操作Behavior行为
error(Default) MongoDB rejects any insert or update that violates the validation criteria.MongoDB拒绝任何违反验证标准的插入或更新。
warnMongoDB allows the operation to proceed, but records the violation in the MongoDB log.MongoDB允许操作继续,但在MongoDB日志中记录违规行为。

Option 1: Reject Invalid Documents选项1:拒绝无效文档

The following procedure shows how to create a schema validation that rejects invalid documents.以下过程显示如何创建拒绝无效文档的架构验证。

1

Create a collection with 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.validationActionerror导致MongoDB拒绝任何无效文档,并阻止它们插入集合中。

2

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:该文档违反了验证规则,因为:

  • The email field does not match the regular expression pattern. email字段与正则表达式模式不匹配。The email 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日志中。

1

Create a collection with 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. validationActionwarn允许将无效文档插入集合中。Invalid documents are recorded in the MongoDB log.无效文档记录在MongoDB日志中。

2

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:该文档违反了验证规则,因为:

  • The email field does not match the regular expression pattern. email字段与正则表达式模式不匹配。The email field must end in @mongodb.com.email字段必须以@mongodb.com结尾。
  • It is missing the required phone field.它缺少必需的phone字段。
3

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

Learn More了解更多信息