- Data Models >
- Schema Validation
Schema Validation¶
On this page
MongoDB provides the capability to perform schema validation during updates and insertions.
Specify Validation Rules¶
Validation rules are on a per-collection basis.
To specify validation rules when creating a new collection, use
db.createCollection() with the validator option.
To add document validation to an existing collection, use
collMod command with the validator option.
MongoDB also provides the following related options:
validationLeveloption, which determines how strictly MongoDB applies validation rules to existing documents during an update.validationActionoption, which determines whether MongoDB shoulderrorand reject documents that violate the validation rules orwarnabout the violations in the log but allow invalid documents.
JSON Schema¶
MongoDB supports JSON Schema validation. To specify JSON Schema validation,
use the $jsonSchema operator in your validator expression.
Note
JSON Schema is the recommended means of performing schema validation.
For example, the following example specifies validation rules using JSON schema:
For more information, see $jsonSchema.
bsonType definitions can be found on the BSON Types page.
Other Query Expressions¶
In addition to JSON Schema validation that uses the
$jsonSchema query operator, MongoDB supports
validation with other query operators, with the exception of:
For example, the following example specifies validator rules using the query expression:
See also
Behavior and Examples¶
Validation occurs during updates and inserts. When you add validation to a collection, existing documents do not undergo validation checks until modification.
Validation on Existing Documents¶
To perform validation checks on existing documents, use the
validate command or the db.collection.validate()
shell helper.
The validationLevel option determines which operations MongoDB
applies the validation rules:
- If the
validationLevelisstrict(the default), MongoDB applies validation rules to all inserts and updates. - If the
validationLevelismoderate, MongoDB applies validation rules to inserts and to updates to existing documents that already fulfill the validation criteria. With themoderatelevel, updates to existing documents that do not fulfill the validation criteria are not checked for validity.
For example, create a contacts collection with the following
documents:
Issue the following command to add a validator to the contacts
collection:
The contacts collection now has a validator with the moderate
validationLevel:
- If you attempted to update the document with
_id: 1, MongoDB would apply the new validation rules since the existing document matches the criteria. - In contrast, MongoDB will not apply validation rules to updates to
the document with
_id: 2as it does not meet the validation rules.
Starting in MongoDB version 5.0, the validator returns detailed error information when a validation condition isn’t met. The error output is exhaustive - all errors are reported, not just the first one.
Important
The error output is intended for human consumption. It may change in the future and should not be relied upon in scripts.
In the next example, neither of the updates is consistent with the
validation rule we created above that requires name to be a string.
The output below shows that the document with _id: 1 fails
validation with a detailed explanation, as shown in the errInfo
object. The update succeeds for the document with _id: 2 since this
document did not meet the initial criteria when validation was added.
To disable validation entirely, you can set validationLevel to
off.
Accept or Reject Invalid Documents¶
The validationAction option determines how MongoDB handles
documents that violate the validation rules:
- If the
validationActioniserror(the default), MongoDB rejects any insert or update that violates the validation criteria. - If the
validationActioniswarn, MongoDB logs any violations but allows the insertion or update to proceed.
For example, create a contacts2 collection with the following JSON
Schema validator:
For example, the following insert operation violates the validation rule:
However, since the validationAction is warn, MongoDB only
logs the validation violation message and allows the operation to
proceed. Run the following command to view the MongoDB logs:
Depending on collection usage, this command might return a lot of data. The validation error (one long line in the log, reformatted here for readability) contains information like this:
Use Title and Description Fields to Clarify Validation Rules¶
Starting in MongoDB 5.1, when a document fails schema validation, MongoDB includes the validation title
and description in the error response. You can use these fields to
provide a clearer explanation of the validation when the rules
are not immediately clear, such as when using regular expressions.
Consider a users collection with the following schema validation:
The pattern field indicates that all email fields must
end with @mongodb.com. If you try to insert a document that
does not match the pattern, MongoDB includes the validation
title and description in the error output:
Input:
Output:
Note
The validation error output is formatted differently in the legacy
mongo shell.
Restrictions¶
You cannot specify a validator for collections in the admin,
local, and config databases.
You cannot specify a validator for system.* collections.
Bypass Document Validation¶
Users can bypass document validation using the
bypassDocumentValidation option.
The following commands can bypass validation per operation using the
new option bypassDocumentValidation:
applyOpscommandfindAndModifycommand anddb.collection.findAndModify()methodmapReducecommand anddb.collection.mapReduce()methodinsertcommandupdatecommand$outand$mergestages for theaggregatecommand anddb.collection.aggregate()method
For deployments that have enabled access control, to bypass document
validation, the authenticated user must have
bypassDocumentValidation action. The built-in roles
dbAdmin and restore provide this action.