Docs Menu
Docs Home
/ /

Schema Validation

Schema validation lets you create validation rules for your fields, such as allowed data types and value ranges.

MongoDB uses a flexible schema model, which means that documents in a collection do not need to have the same fields or data types by default. Once you've established an application schema, you can use schema validation to ensure there are no unintended schema changes or improper data types.

You can implement schema validation in the UI for deployments hosted in MongoDB Atlas.

Your schema validation needs depend on how users use your application. MongoDB's flexible schema makes it easy to evolve your data model, especially in the early stages of development. However, as your data model stabilizes, schema validation can be a helpful way to ensure the data looks as intended. Schema validation is most useful for an established application where you have a good sense of how to organize your data.

Note

Schema validation rules are also flexible, so they don't need to cover every field in a document, unless your application requires that they do.

You can use schema validation in the following scenarios:

  • For an events collection, ensure that the start_date field is only stored as a date and not a string, so connecting applications don't use unexpected types.

  • For a store collection, ensure that the accepted_credit_cards field belongs to a list of credit cards that your store accepts, such as ["Visa", "MasterCard", "American Express"]. This validation prevents a user from entering an unsupported credit card value.

  • For a students collection, ensure that the gpa field is always a positive floating point number. This validation prevents errors during data entry.

After you add schema validation rules to a collection:

  • All document inserts must match the rules.

  • The schema validation level defines how the rules are applied to existing documents and document updates. To learn more, see Specify Validation Level for Existing Documents.

To find documents in a collection that don't match the schema validation rules, see Find Documents that Don't Match the Schema.

By default, when an insert or update operation would result in an invalid document, MongoDB rejects the operation and does not write the document to the collection.

Alternatively, you can configure MongoDB to allow invalid documents and log warnings when schema violations occur.

To learn more, see Choose How to Handle Invalid Documents.

For common tasks involving schema validation, see the following pages:

To learn about MongoDB's flexible schema model, see Data Modeling in MongoDB.

Back

Use Embedding

Earn a Skill Badge

Master "Relational to Document Model" for free!

Learn more

On this page