我的MongoDB中有一个包含1300万条记录的集合。不幸的是,当我创建这个集合时,没有为它创建任何模式。我想知道是否有任何方法可以添加JSON模式,而不是备份整个数据库,创建模式并上传所有数据。
您可以使用collMod
命令将JSON模式应用于现有集合,以将新的JSON模式添加到集合https://docs.mongodb.com/manual/core/schema-validation/。以下是一个例子。但是,它仅适用于新的写入操作,它不会对集合中的现有文档运行。
db.runCommand( {
collMod: "contacts",
validator: { $jsonSchema: {
bsonType: "object",
required: [ "phone", "name" ],
properties: {
phone: {
bsonType: "string",
description: "must be a string and is required"
},
name: {
bsonType: "string",
description: "must be a string and is required"
}
}
} },
validationLevel: "moderate"
} )