Mongodb - 给现有集合添加模式

9

我在MongoDB中有一个包含1300万条记录的集合。不幸的是,当我创建这个集合时并没有为其创建模式。我想知道是否有任何方法可以添加一个JSON模式,而不是备份整个数据库,创建模式,然后上传所有数据。

1个回答

12

使用collMod命令将JSON schema应用于现有集合,以向集合添加新的JSON schema。具体请参见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"
} )

如何在使用MongoDB驱动程序的C#中运行此代码? - supernerd
FYI: $jsonSchema 文档: https://docs.mongodb.com/manual/reference/operator/query/jsonSchema/ - DeBraid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接