Docs HomeDevelop ApplicationsMongoDB Manual

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可以:

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拒绝任何违反验证标准的插入或更新。
warn MongoDB allows the operation to proceed, but records the violation in the MongoDB log.MongoDB允许操作继续,但在MongoDB日志中记录违规情况。

Steps: Reject Invalid Documents步骤:拒绝无效文档

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 match the regular expression pattern"
         },
         status: {
            enum: [ "Unknown", "Incomplete" ],
            description: "can only be one of the enum values"
         }
      }
   } },
   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.试图插入无效文档。

The following insert operation violates the validation rule because status is not one of the allowed values (Unknown or Incomplete):以下插入操作违反了验证规则,因为status不是允许的值之一(UnknownIncomplete):

db.contacts.insertOne( { name: "Amanda", status: "Updated" } )

The operation fails with the following error:操作失败,出现以下错误:

MongoServerError: Document failed validation
Additional information: {
  failingDocumentId: ObjectId("62b384321340c60e11b98a84"),
  details: {
    operatorName: '$jsonSchema',
    schemaRulesNotSatisfied: [
      {
        operatorName: 'properties',
        propertiesNotSatisfied: [
          {
            propertyName: 'status',
            description: 'can only be one of the enum values',
            details: [
              {
                operatorName: 'enum',
                specifiedAs: { enum: [ 'Unknown', 'Incomplete' ] },
                reason: 'value was not found in enum',
                consideredValue: 'Updated'
              }
            ]
          }
        ]
      },
      {
        operatorName: 'required',
        specifiedAs: { required: [ 'phone' ] },
        missingProperties: [ 'phone' ]
      }
    ]
  }
}

Steps: Allow Invalid Documents and Record Them in the Log步骤:允许无效文档并将其记录在日志中

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 match the regular expression pattern"
         },
         status: {
            enum: [ "Unknown", "Incomplete" ],
            description: "can only be one of the enum values"
         }
      }
   } },
   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.试图插入无效文档。

The following insert operation violates the validation rule because status is not one of the allowed values (Unknown or Incomplete):以下插入操作违反了验证规则,因为status不是允许的值之一(UnknownIncomplete):

db.contacts2.insertOne( { name: "Amanda", status: "Updated" } )
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-06-30T18:05:22.088-04:00"
   },
   "s":"W",
   "c":"STORAGE",
   "id":20294,
   "ctx":"conn61",
   "msg":"Document would fail validation",
   "attr":{
      "namespace":"test.contacts2",
      "document":{
         "_id":{
            "$oid":"62be1e2273c105dde923129f"
         },
         "name":"Amanda",
         "status":"Updated"
      },
      "errInfo":{
         "failingDocumentId":{
            "$oid":"62be1e2273c105dde923129f"
         },
         "details":{
            "operatorName":"$jsonSchema",
            "schemaRulesNotSatisfied":[
               {
                  "operatorName":"properties",
                  "propertiesNotSatisfied":[
                     {
                        "propertyName":"status",
                        "description":"can only be one of the enum values",
                        "details":[
                           {
                              "operatorName":"enum",
                              "specifiedAs":{
                                 "enum":[
                                    "Unknown",
                                    "Incomplete"
                                 ]
                              },
                              "reason":"value was not found in enum",
                              "consideredValue":"Updated"
                           }
                        ]
                     }
                  ]
               },
               {
                  "operatorName":"required",
                  "specifiedAs":{
                     "required":[
                        "phone"
                     ]
                  },
                  "missingProperties":[
                     "phone"
                  ]
               }
            ]
         }
      }
   }
}

Learn More

←  Specify Validation Level for Existing Documents指定现有文档的验证级别Query for and Modify Valid or Invalid Documents查询和修改有效或无效文档 →