Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb - Add Schema for existing collection

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.

like image 799
olegario Avatar asked Mar 06 '19 14:03

olegario


People also ask

How do I add a schema to a collection in MongoDB?

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.

Can we change schema in MongoDB?

Collections in MongoDB do not have a fixed schema, or requirement for all documents in a collection to have the same schema. You can definitely add or remove fields, change field types, or update JSON Schema validation without recreating a collection.

Can MongoDB have schema?

Data in MongoDB has a flexible schema. Collections do not enforce document structure by default. This flexibility gives you data-modeling choices to match your application and its performance requirements.

How do I create a schema in MongoDB Atlas?

Overview. You can create a schema for your App in one of two ways: Create a Realm Object Model from an App Services Schema: If you have data in your MongoDB Atlas cluster already, MongoDB generates an App Services Schema by sampling your data.


1 Answers

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"
} )
like image 96
christkv Avatar answered Sep 16 '22 12:09

christkv