Schema Validation

New in version 3.2.

MongoDB provides the capability to perform schema validation duringupdates and insertions.

Specify Validation Rules

Validation rules are on a per-collection basis.

To specify validation rules when creating a new collection, usedb.createCollection() with the validator option.

To add document validation to an existing collection, usecollMod command with the validator option.

MongoDB also provides the following related options:

  • validationLevel option, which determines how strictly MongoDBapplies validation rules to existing documents during an update, and
  • validationAction option, which determines whether MongoDB shoulderror and reject documents that violate the validation rules orwarn about the violations in the log but allow invalid documents.

JSON Schema

New in version 3.6.

Starting in version 3.6, MongoDB supports JSON Schema validation. Tospecify JSON Schema validation, use the $jsonSchema operatorin your validator expression.

Note

JSON Schema is the recommended means of performing schema validation.

For example, the following example specifies validation rules usingJSON schema:

  1. db.createCollection("students", {
  2. validator: {
  3. $jsonSchema: {
  4. bsonType: "object",
  5. required: [ "name", "year", "major", "address" ],
  6. properties: {
  7. name: {
  8. bsonType: "string",
  9. description: "must be a string and is required"
  10. },
  11. year: {
  12. bsonType: "int",
  13. minimum: 2017,
  14. maximum: 3017,
  15. description: "must be an integer in [ 2017, 3017 ] and is required"
  16. },
  17. major: {
  18. enum: [ "Math", "English", "Computer Science", "History", null ],
  19. description: "can only be one of the enum values and is required"
  20. },
  21. gpa: {
  22. bsonType: [ "double" ],
  23. description: "must be a double if the field exists"
  24. },
  25. address: {
  26. bsonType: "object",
  27. required: [ "city" ],
  28. properties: {
  29. street: {
  30. bsonType: "string",
  31. description: "must be a string if the field exists"
  32. },
  33. city: {
  34. bsonType: "string",
  35. "description": "must be a string and is required"
  36. }
  37. }
  38. }
  39. }
  40. }
  41. }
  42. })

For more information, see $jsonSchema.

Other Query Expressions

In addition to JSON Schema validation that uses the$jsonSchema query operator, MongoDB supportsvalidation with other query operators, with the exception of the $near,$nearSphere, $text, and $where operators.

For example, the following example specifies validator rules using thequery expression:

  1. db.createCollection( "contacts",
  2. { validator: { $or:
  3. [
  4. { phone: { $type: "string" } },
  5. { email: { $regex: /@mongodb\.com$/ } },
  6. { status: { $in: [ "Unknown", "Incomplete" ] } }
  7. ]
  8. }
  9. } )

See also

query operators

Behavior

Validation occurs during updates and inserts. When you add validation toa collection, existing documents do not undergo validation checks untilmodification.

Existing Documents

The validationLevel option determines which operations MongoDBapplies the validation rules:

  • If the validationLevel is strict (the default), MongoDBapplies validation rules to all inserts and updates.
  • If the validationLevel is moderate, MongoDB appliesvalidation rules to inserts and to updates to existing documents thatalready fulfill the validation criteria. With the moderate level,updates to existing documents that do not fulfill the validationcriteria are not checked for validity.

For example, create a contacts collection with the followingdocuments:

  1. db.contacts.insert([
  2. { "_id": 1, "name": "Anne", "phone": "+1 555 123 456", "city": "London", "status": "Complete" },
  3. { "_id": 2, "name": "Ivan", "city": "Vancouver" }
  4. ])

Issue the following command to add a validator to the contactscollection:

  1. db.runCommand( {
  2. collMod: "contacts",
  3. validator: { $jsonSchema: {
  4. bsonType: "object",
  5. required: [ "phone", "name" ],
  6. properties: {
  7. phone: {
  8. bsonType: "string",
  9. description: "must be a string and is required"
  10. },
  11. name: {
  12. bsonType: "string",
  13. description: "must be a string and is required"
  14. }
  15. }
  16. } },
  17. validationLevel: "moderate"
  18. } )

The contacts collection now has a validator with the moderatevalidationLevel:

  • If you attempted to update the document with _id of 1,MongoDB would apply the validation rules since the existing documentmatches the criteria.
  • In contrast, MongoDB will not apply validation rules to updates tothe document with _id of 2 as it does not meet thevalidation rules.

To disable validation entirely, you can set validationLevel tooff.

Accept or Reject Invalid Documents

The validationAction option determines how MongoDB handlesdocuments that violate the validation rules:

  • If the validationAction is error (the default), MongoDBrejects any insert or update that violates the validation criteria.
  • If the validationAction is warn, MongoDB logs any violationsbut allows the insertion or update to proceed.

For example, create a contacts2 collection with the following JSONSchema validator:

  1. db.createCollection( "contacts2", {
  2. validator: { $jsonSchema: {
  3. bsonType: "object",
  4. required: [ "phone" ],
  5. properties: {
  6. phone: {
  7. bsonType: "string",
  8. description: "must be a string and is required"
  9. },
  10. email: {
  11. bsonType : "string",
  12. pattern : "@mongodb\.com$",
  13. description: "must be a string and match the regular expression pattern"
  14. },
  15. status: {
  16. enum: [ "Unknown", "Incomplete" ],
  17. description: "can only be one of the enum values"
  18. }
  19. }
  20. } },
  21. validationAction: "warn"
  22. } )

With the warn validationAction, MongoDB logs anyviolations but allows the insertion or update to proceed.

For example, the following insert operation violates the validation rule:

  1. db.contacts2.insert( { name: "Amanda", status: "Updated" } )

However, since the validationAction is warn only, MongoDB onlylogs the validation violation message and allows the operation toproceed:

  1. 2017-12-01T12:31:23.738-0500 W STORAGE [conn1] Document would fail validation collection: example.contacts2 doc: { _id: ObjectId('5a2191ebacbbfc2bdc4dcffc'), name: "Amanda", status: "Updated" }

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 thebypassDocumentValidation option.

The following commands can bypass validation per operation using thenew option bypassDocumentValidation:

For deployments that have enabled access control, to bypass documentvalidation, the authenticated user must havebypassDocumentValidation action. The built-in rolesdbAdmin and restore provide this action.

Additional Information

See also

collMod, db.createCollection(),db.getCollectionInfos().