$jsonSchema

Definition

$jsonSchema

New in version 3.6.

The $jsonSchema operator matches documents that satisfy the specified JSON Schema.

The $jsonSchema operator expression has the following syntax:

{ $jsonSchema: <JSON Schema object> }

Where the JSON Schema object is formatted according to draft 4 of the JSON Schema standard .

{ <keyword1>: <value1>, ... }

For example:

{
  $jsonSchema: {
     required: [ "name", "major", "gpa", "address" ],
     properties: {
        name: {
           bsonType: "string",
           description: "must be a string and is required"
        },
        address: {
           bsonType: "object",
           required: [ "zipcode" ],
           properties: {
               "street": { bsonType: "string" },
               "zipcode": { bsonType: "string" }
           }
        }
     }
  }
}

For a list of keywords supported by MongoDB, see Available Keywords.

Note

MongoDB supports draft 4 of JSON Schema, including core specification and validation specification , with some differences. See Extensions and Omissions for details.

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

Behavior

Feature Compatibility

The featureCompatibilityVersion must be set to "3.6" or higher in order to use $jsonSchema.

Document Validator

You can use $jsonSchema in a document validator to enforce the specified schema on insert and update operations:

db.createCollection( <collection>, { validator: { $jsonSchema: <schema> } } )
db.runCommand( { collMod: <collection>, validator:{ $jsonSchema: <schema> } } )

Query Conditions

You can use $jsonSchema in query conditions for read and write operations to find documents in the collection that satisfy the specified schema:

db.collection.find( { $jsonSchema: <schema> } )
db.collection.aggregate( [ { $match: { $jsonSchema: <schema> } } ] )
db.collection.updateMany( { $jsonSchema: <schema> }, <update> )
db.collection.deleteOne( { $jsonSchema: <schema> } )

To find documents in the collection that do not satisfy the specified schema, use the $jsonSchema expression in a $nor expression. For example:

db.collection.find( { $nor: [ { $jsonSchema: <schema> } ] } )
db.collection.aggregate( [ { $match: { $nor: [ { $jsonSchema: <schema> } ] } }, ... ] )
db.collection.updateMany( { $nor: [ { $jsonSchema: <schema> } ] }, <update> )
db.collection.deleteOne( { $nor: [ { $jsonSchema: <schema> } ] } )

Examples

Schema Validation

The following db.createCollection() method creates a collection named students and uses the $jsonSchema operator to set schema validation rules:

db.createCollection("students", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         required: [ "name", "year", "major", "address" ],
         properties: {
            name: {
               bsonType: "string",
               description: "must be a string and is required"
            },
            year: {
               bsonType: "int",
               minimum: 2017,
               maximum: 3017,
               description: "must be an integer in [ 2017, 3017 ] and is required"
            },
            major: {
               enum: [ "Math", "English", "Computer Science", "History", null ],
               description: "can only be one of the enum values and is required"
            },
            gpa: {
               bsonType: [ "double" ],
               description: "must be a double if the field exists"
            },
            address: {
               bsonType: "object",
               required: [ "city" ],
               properties: {
                  street: {
                     bsonType: "string",
                     description: "must be a string if the field exists"
                  },
                  city: {
                     bsonType: "string",
                     "description": "must be a string and is required"
                  }
               }
            }
         }
      }
   }
})

Given the created validator for the collection, the following insert operation will fail because gpa is an integer when the validator requires a double.

db.students.insert({
   name: "Alice",
   year: NumberInt(2019),
   major: "History",
   gpa: NumberInt(3),
   address: {
      city: "NYC",
      street: "33rd Street"
   }
})

The operation returns the following error:

WriteResult({
   "nInserted" : 0,
   "writeError" : {
      "code" : 121,
      "errmsg" : "Document failed validation"
   }
})

After changing the gpa to a double, the insert succeeds:

db.students.insert({
   name: "Alice",
   year: NumberInt(2019),
   major: "History",
   gpa: 3.0,
   address: {
      city: "NYC",
      street: "33rd Street"
   }
})

The operation returns the following:

WriteResult({ "nInserted" : 1 })

Query Conditions

You can use $jsonSchema in query conditions for read and write operations to find documents in the collection that satisfy the specified schema.

For example, create a sample collection inventory with the following documents:

db.inventory.insertMany([
   { item: "journal", qty: NumberInt(25), size: { h: 14, w: 21, uom: "cm" }, instock: true },
   { item: "notebook", qty: NumberInt(50), size: { h: 8.5, w: 11, uom: "in" }, instock: true },
   { item: "paper", qty: NumberInt(100), size: { h: 8.5, w: 11, uom: "in" }, instock: 1 },
   { item: "planner", qty: NumberInt(75), size: { h: 22.85, w: 30, uom: "cm" }, instock: 1 },
   { item: "postca
首页