最近我对 MongoDB 做了一些阅读和实验 db.collection("name").validate()
操作(见 here)。当您设置数据库时,这很好用,但如果在添加验证之前集合中已经有文档,则不会检查这些文档中的任何一个以进行验证。如何验证 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
关于MongoDB:验证集合中已存在的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43098343/