Docs Menu
Docs Home
/
MongoDB Manual
/

Schema Validation

On this page

  • When to Use Schema Validation
  • When MongoDB Checks Validation
  • What Happens When a Document Fails Validation
  • Tasks
  • Learn More

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.

Your schema validation needs depend on how users use your application. When your application is in the early stages of development, schema validation may impose unhelpful restrictions because you don't know how you want to organize your data. Specifically, the fields in your collections may change over time.

Schema validation is most useful for an established application where you have a good sense of how to organize your data. You can use schema validation in the following scenarios:

  • For a users collection, ensure that the password field is only stored as a string. This validation prevents users from saving their password as an unexpected data type, like an image.

  • For a sales collection, ensure that the item field belongs to a list of items that your store sells. This validation prevents a user from accidentally misspelling an item name when entering sales data.

  • For a students collection, ensure that the gpa field is always a positive number. This validation catches typos during data entry.

When you create a new collection with schema validation, MongoDB checks validation during updates and inserts in that collection.

When you add validation to an existing, non-empty collection:

  • Newly inserted documents are checked for validation.

  • Documents already existing in your collection are not checked for validation until they are modified. Specific behavior for existing documents depends on your chosen validation level. To learn more, see Specify Validation Level for Existing Documents.

Adding validation to an existing collection does not enforce validation on existing documents. To check a collection for invalid documents, use the validate command.

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 Introduction.

Back

Data Modeling Introduction