MongoDB:验证集合中已存在的文档



最近我做了一些阅读和实验MongoDB db.collection("name").validate()操作(见这里(。在设置数据库时,这很好用,但是如果在添加验证之前集合中已有文档,则不会检查这些文档以进行验证。如何验证mongoDB中已经存在的文档?

如果您已将文档插入集合中,现在又要验证集合。

为此,您必须使用 runCommand。在 runCommand 中,您必须指定要验证的集合名称,并提供要应用验证的数据字段-

前任-

db.runCommand( {
   collMod: "collectionName",
   validator: { $jsonSchema: {
      bsonType: "object",
      required: [ "variable1", "variable2" ],
      properties: {
         variable1: {
            bsonType: "string",
            description: "must be a string and is required"
         },
         variable2: {
            bsonType: "string",
            description: "must be a string and is required"
         }
      }
   } },
   validationLevel: "moderate"
} )

有关更多详细信息,您可以访问-https://docs.mongodb.com/manual/core/schema-validation/#existing-documents

最新更新