Document Validation

On this page

New in version 3.2.

MongoDB provides the capability to validate documents during updates and insertions. Validation rules are specified on a per-collection basis using thevalidatoroption, which takes a document that specifies the validation rules or expressions. Specify the expressions using anyquery operators, with the exception of$near,$nearSphere,$text, and$where.

Add document validation to an existing collection using thecollModcommand with thevalidatoroption. You can also specify document validation rules when creating a new collection usingdb.createCollection()with thevalidatoroption, as in the following:

  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. } )

MongoDB also provides thevalidationLeveloption, which determines how strictly MongoDB applies validation rules to existing documents during an update, and thevalidationActionoption, which determines whether MongoDB shoulderrorand reject documents that violate the validation rules orwarnabout the violations in the log but allow invalid documents.

Behavior

Validation occurs during updates and inserts. When you add validation to a collection, existing documents do not undergo validation checks until modification.

Existing Documents

You can control how MongoDB handles existing documents using thevalidationLeveloption.

By default,validationLevelisstrictand MongoDB applies validation rules to all inserts and updates. SettingvalidationLeveltomoderateapplies validation rules to inserts and to updates to existing documents that fulfill the validation criteria. With themoderatelevel, updates to existing documents that do not fulfill the validation criteria are not checked for validity.

EXAMPLE

Consider the following documents in acontactscollection:

  1. {
  2. "_id": "125876",
  3. "name": "Anne",
  4. "phone": "+1 555 123 456",
  5. "city": "London",
  6. "status": "Complete"
  7. },
  8. {
  9. "_id": "860000",
  10. "name": "Ivan",
  11. "city": "Vancouver"
  12. }

Issue the following command to add a validator to thecontactscollection:

  1. db.runCommand( {
  2. collMod: "contacts",
  3. validator: { $or: [ { phone: { $exists: true } }, { email: { $exists: true } } ] },
  4. validationLevel: "moderate"
  5. } )

Thecontactscollection now has a validator with themoderatevalidationLevel. If you attempted to update the document with_idof125876, MongoDB would apply validation rules since the existing document matches the criteria. In contrast, MongoDB will not apply validation rules to updates to the document with_idof860000as it does not meet the validation rules.

To disable validation entirely, you can setvalidationLeveltooff.

Accept or Reject Invalid Documents

ThevalidationActionoption determines how MongoDB handles documents that violate the validation rules.

By default,validationActioniserrorand MongoDB rejects any insertion or update that violates the validation criteria. WhenvalidationActionis set towarn, MongoDB logs any violations but allows the insertion or update to proceed.

EXAMPLE

The following example creates acontactscollection with a validator that specifies that inserted or updated documents should match at least one of three following conditions:

  • the
    phone
    field is a string
  • the
    email
    field matches the regular expression
  • the
    status
    field is either
    Unknown
    or
    Incomplete
    .
  1. db.createCollection( "contacts",
  2. {
  3. validator: { $or:
  4. [
  5. { phone: { $type: "string" } },
  6. { email: { $regex: /@mongodb\.com$/ } },
  7. { status: { $in: [ "Unknown", "Incomplete" ] } }
  8. ]
  9. },
  10. validationAction: "warn"
  11. }
  12. )

With the validator in place, the following insert operation fails the validation rules, but since thevalidationActioniswarn, the write operation logs the failure and succeeds.

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

The log includes the full namespace of the collection and the document that failed the validation rules, as well as the time of the operation:

  1. 2015-10-15T11:20:44.260-0400 W STORAGE [conn3] Document would fail validation collection: example.contacts doc: { _id: ObjectId('561fc44c067a5d85b96274e4'), name: "Amanda", status: "Updated" }

Restrictions

You cannot specify a validator for collections in theadmin,local, andconfigdatabases.

You cannot specify a validator forsystem.*collections.

Bypass Document Validation

Users can bypass document validation using thebypassDocumentValidationoption. For a list of commands that support thebypassDocumentValidationoption, seeDocument Validation.

For deployments that have enabled access control, to bypass document validation, the authenticated user must havebypassDocumentValidationaction. The built-in rolesdbAdminandrestoreprovide this action.

Additional Information

SEE ALSO

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