Can I update a schema?

Once a schema is created, is it possible to update it?

For example, can I change the type from “string” to “enum:[]”

Depending on how you set up your schema you might have to shuffle data around, e.g., create a new collection and move the data over from the old collection, but it’s not rocket science.

I see.

To be clear then, there is no database command to db.updateScheme()

^^ nothing like this?

Id have to recreate and move the data?

Welcome to the MongoDB Community @Kevin_Izevbigie!

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. The only top of mind exceptions would be changing an immutable field like _id or changing a document’s shard key value in MongoDB server versions older than 4.2.

Can you provide more information what you are referring to as schema? Do you mean JSON schema validation (which is enforced when documents are inserted or updated) or perhaps schema declared in an Object-Document Mapper (ODM) like Mongoose? What MongoDB driver and version are you using?


1 Like

That’s how I was interpreting the question, @Stennie … maybe I jumped too quickly to a conclusion.

Hi Both – this line is what I was talking about. When a Collection has been created and I defined a schema, how do I change a field type or remove a field? Or, most importantly, update the JSON schema validation rule set that I defined previously.



Hi @Kevin_Izevbigie,

Borrowing from discussion on a similar question in the context of the Node.js driver (How to use MongoDB for nodejs to modify the schema of an existing collection? - #2 by Stennie):

The essential step is:

… and a handy hint for previewing the effects of a schema validation change:

Lastly, schema validation in MongoDB 5.0+ has improved error messages that will help you understand why a document fails schema validation: Improved Error Messages for Schema Validation in MongoDB 5.0.

If you happen to be using an older version of MongoDB server or would be like to validate earlier in your application logic (eg frontend or application code), you should be able to find a JSON Schema Validator library or package in your preferred implementation language. MongoDB’s JSON Schema implementation adds the bsonType keyword and has a few omissions, but should be straightforward to add if not already supported by your chosen validation package.



This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.