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 thevalidator
option, 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 thecollMod
command with thevalidator
option. You can also specify document validation rules when creating a new collection usingdb.createCollection()
with thevalidator
option, as in the following:
db.createCollection( "contacts",
{ validator: { $or:
[
{ phone: { $type: "string" } },
{ email: { $regex: /@mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
]
}
} )
MongoDB also provides thevalidationLevel
option, which determines how strictly MongoDB applies validation rules to existing documents during an update, and thevalidationAction
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.
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 thevalidationLevel
option.
By default,validationLevel
isstrict
and MongoDB applies validation rules to all inserts and updates. SettingvalidationLevel
tomoderate
applies validation rules to inserts and to updates to existing documents that fulfill the validation criteria. With themoderate
level, updates to existing documents that do not fulfill the validation criteria are not checked for validity.
EXAMPLE
Consider the following documents in acontacts
collection:
{
"_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 thecontacts
collection:
db.runCommand( {
collMod: "contacts",
validator: { $or: [ { phone: { $exists: true } }, { email: { $exists: true } } ] },
validationLevel: "moderate"
} )
Thecontacts
collection now has a validator with themoderate
validationLevel. If you attempted to update the document with_id
of125876
, 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_id
of860000
as it does not meet the validation rules.
To disable validation entirely, you can setvalidationLevel
tooff
.
Accept or Reject Invalid Documents
ThevalidationAction
option determines how MongoDB handles documents that violate the validation rules.
By default,validationAction
iserror
and MongoDB rejects any insertion or update that violates the validation criteria. WhenvalidationAction
is set towarn
, MongoDB logs any violations but allows the insertion or update to proceed.
EXAMPLE
The following example creates acontacts
collection 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 eitherUnknown
orIncomplete
.
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 thevalidationAction
iswarn
, 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
, andconfig
databases.
You cannot specify a validator forsystem.*
collections.
Bypass Document Validation
Users can bypass document validation using thebypassDocumentValidation
option. For a list of commands that support thebypassDocumentValidation
option, seeDocument Validation.
For deployments that have enabled access control, to bypass document validation, the authenticated user must havebypassDocumentValidation
action. The built-in rolesdbAdmin
andrestore
provide this action.
Additional Information
SEE ALSO