Specify JSON Schema Validation (original) (raw)

JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. You can use JSON schema to specify validation rules for your fields in a human-readable format.

You can use JSON schema validation for deployments hosted in the following environments:

MongoDB supports draft 4 of JSON Schema, including core specification and validation specification, with some differences. For details, see Extensions andOmissions.

For more information about JSON Schema, see the official website.

You can't specify schema validation for:

If you have Client-Side Field Level Encryption or Queryable Encryption enabled on a collection, validation is subject to the following restrictions:

In this example, you create a students collection with validation rules and observe the results after you attempt to insert an invalid document.

In mongosh, run the following command to create a students collection and use the$jsonSchema operator to set schema validation rules:


db.createCollection("students", {

   validator: {

      $jsonSchema: {

         bsonType: "object",

         title: "Student Object Validation",

         required: [ "address", "major", "name", "year" ],

         properties: {

            name: {

               bsonType: "string",

               description: "'name' must be a string and is required"

            },

            year: {

               bsonType: "int",

               minimum: 2017,

               maximum: 3017,

               description: "'year' must be an integer in [ 2017, 3017 ] and is required"

            },

            gpa: {

               bsonType: [ "double" ],

               description: "'gpa' must be a double if the field exists"

            }

         }

      }

   }

} )

Tip

Clarify Rules with Title and Description Fields

You can use title and description fields to provide an explanation of validation rules when the rules are not immediately clear. When a document fails validation, MongoDB includes these fields in the error output.

Run the following command. The insert operation fails because gpa is an integer when the validator requires adouble.


db.students.insertOne( {

   name: "Alice",

   year: Int32( 2019 ),

   major: "History",

   gpa: Int32(3),

   address: {

      city: "NYC",

      street: "33rd Street"

   }

} )


MongoServerError: Document failed validation

Additional information: {

  failingDocumentId: ObjectId("630d093a931191850b40d0a9"),

  details: {

    operatorName: '$jsonSchema',

    title: 'Student Object Validation',

    schemaRulesNotSatisfied: [

      {

        operatorName: 'properties',

        propertiesNotSatisfied: [

          {

            propertyName: 'gpa',

            description: "'gpa' must be a double if the field exists",

            details: [

              {

                operatorName: 'bsonType',

                specifiedAs: { bsonType: [ 'double' ] },

                reason: 'type did not match',

                consideredValue: 3,

                consideredType: 'int'

              }

            ]

          }

        ]

      }

    ]

  }

}

Tip

By default, mongosh prints nested objects up to six levels deep. To print all nested objects to their full depth, set inspectDepth to Infinity.


config.set("inspectDepth", Infinity)

If you change the gpa field value to a double type, the insert operation succeeds. Run the following command to insert the valid document:


db.students.insertOne( {

   name: "Alice",

   year: NumberInt(2019),

   major: "History",

   gpa: Double(3.0),

   address: {

      city: "NYC",

      street: "33rd Street"

   }

} )

To confirm that you've successfully inserted the document, run the following command to query the students collection:


[

   {

      _id: ObjectId("62bb413014b92d148400f7a5"),

      name: 'Alice',

      year: 2019,

      major: 'History',

      gpa: 3,

      address: { city: 'NYC', street: '33rd Street' }

   }

]

Tip

You can combine JSON Schema validation with query operator validation.

For example, consider a sales collection with this schema validation:


 db.createCollection("sales", {

   validator: {

     "$and": [

       // Validation with query operators

       {

         "$expr": {

           "$lt": ["$lineItems.discountedPrice", "$lineItems.price"]

         }

       },

       // Validation with JSON Schema

       {

         "$jsonSchema": {

           "properties": {

             "items": { "bsonType": "array" }

           }

          }

        }

      ]

    }

  }

)

The preceding validation enforces these rules for documents in thesales collection: