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:

db.createCollection( "contacts",
   { validator: { $or:
      [
         { phone: { $type: "string" } },
         { email: { $regex: /@mongodb\.com$/ } },
         { status: { $in: [ "Unknown", "Incomplete" ] } }
      ]
   }
} )

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:

{
   "_id": "125876",
   "name": "Anne",
   "phone": "+1 555 123 456",
   "city": "London",
   "status": "Complete"
},
{
   "_id": "860000",
   "name": "Ivan",
   "city": "Vancouver"
}

Issue the following command to add a validator to thecontactscollection:

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

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 .
db.createCollection( "contacts",
   {
      validator: { $or:
         [
            { phone: { $type: "string" } },
            { email: { $regex: /@mongodb\.com$/ } },
            { status: { $in: [ "Unknown", "Incomplete" ] } }
         ]
      },
      validationAction: "warn"
   }
)

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

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:

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

results matching ""

    No results matching ""