Mongodb - 为现有集合添加架构 [英] Mongodb - Add Schema for existing collection

查看:60
本文介绍了Mongodb - 为现有集合添加架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a collection in my MongoDB with 13 million of records. Unfortanelly, when I created this collection, no schema was created for it. I would like to know if there is any method that I could add an JSON schema beyond backup the entire the database, create the schema and upload all the data.

推荐答案

您可以使用 collMod 命令将 JSON 架构应用于现有集合,以将新的 JSON 架构添加到集合 https://docs.mongodb.com/manual/core/schema-validation/.下面举个例子.但是,它仅适用于新的写入操作,不会针对集合中的现有文档运行.

You can apply a JSON schema to an existing collection using the collMod command to add a new JSON schema to the collection https://docs.mongodb.com/manual/core/schema-validation/. An example below. However it will only apply to new write operations it will not run against existing documents in the collection.

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 - 为现有集合添加架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆