Schema Validation
On this page
Overview
In this guide, you can learn how to use the Rust driver to implement schema validation for your MongoDB collections.
To implement schema validation, you must provide a JSON schema that consists of a set of a validation rules. If you implement schema validation, the server only allows you to run write operations that follow the validation rules. Use schema validation to restrict data types and value ranges of document fields in a specified collection.
You can define schema validation rules when creating a collection by using
driver methods, or you can add them to an existing collection by using the
collMod
MongoDB command. This guide only describes how to enable schema
validation when creating a collection. To learn more about enabling schema
validation on existing collections, see collMod
in the Server manual.
JSON Schema Validation
Before creating a collection with schema validation rules, you must define a JSON schema.
The JSON schema is a JSON object that contains key-value pairs specifying
the validation rules for your collection. At the top level, this object must
include a $jsonSchema
object. The $jsonSchema
object includes the
following fields:
title: sets an optional description for the schema.
required: specifies a list of required fields for each document in your collection.
properties: sets property requirements for individual fields.
For a full list of JSON schema object fields, see JSON Schema in the Server manual.
Implement Schema Validation
You can implement schema validation by passing your schema and related options
in an instance of CreateCollectionOptions
to the create_collection()
method. You can build a CreateCollectionOptions
instance by using the
CreateCollectionOptions::builder()
method.
Note
Instantiating Options
The Rust driver implements the Builder design pattern for the
creation of many different types, including CreateCollectionOptions
.
You can use each type's builder()
method to construct an options
instance by chaining option builder functions one at a time.
Call the following CreateCollectionOptions::builder()
functions to specify
the validation options for the new collection:
Method | Description |
---|---|
validator() | Specifies validation rules for a collection by passing a JSON schema. For more information, see the JSON Schema Validation section on this page. |
validation_level() | Specifies which insert and update operations are subject to the validation rules. Possible values: |
validation_action() | Specifies whether the driver throws an error or a warning if you insert documents that don't follow the validation rules. Possible values: |
Example
This example creates a collection called survey_answers
with the
following validation specifications:
The
validator()
method receives a JSON schema specifying that theanswer
field in each document must have a value of"yes"
or"no"
.The
validation_action()
method specifies whether the driver raises anError
when a write operation violates a validation rule.The
validation_level()
method specifies that the validation isModerate
, so the validation rules apply only to inserts and updates on existing valid documents.
let validator = doc! { "$jsonSchema": doc! { "bsonType": "object", "title": "Answer Value Validation", "properties": doc! { "answer": doc! { "enum": vec! [ "yes", "no" ], } } } }; let validation_opts = CreateCollectionOptions::builder() .validator(validator) .validation_action(Some(ValidationAction::Error)) .validation_level(Some(ValidationLevel::Moderate)) .build(); db.create_collection("survey_answers", validation_opts).await?;
The following documents follow the validation rules and can be successfully inserted:
{ "_id": { ... }, "question": "Do you like to exercise?", "answer": "yes" }, { "_id": { ... }, "question": "Do you like to play computer games?", "answer": "no" }
However, if you attempt to insert the following document, the server
raises an error because the value of answer
does not match any of
the valid options:
{ "_id": { ... }, "question": "Do you like to exercise?", "answer": "depends on my mood" }
Tip
Bypass Schema Validation
To bypass a collection's validation rules, set the bypass_document_validation
field to true
in the write method's options parameter. This ignores any validation
rules on the collection and any exemptions of them defined by the validation_level
.
To see an example of how to specify this setting in the options for the
insert_one()
method, see the Modify insert_one Behavior section of the Insert Documents guide.
Additional Information
To learn more about the MongoDB Server operations mentioned on this page, see the following documentation in the Server manual:
API Documentation
To learn more about setting validation levels and actions, see the following API documentation:
validation_level for the
validation_level()
helper methodValidationLevel for possible
validation_level
valuesvalidation_action for the
validation_action()
helper methodValidationAction for possible
validation_action
values
To learn more about any other methods or types referenced in this guide, see the following documentation: