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.
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.
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.
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.
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.
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"
} )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With