Schema Validation - VUTP-University/mongodb-cluster GitHub Wiki

Schema validation lets you create validation rules for your fields, such as allowed data types and value ranges.

MongoDB uses a flexible schema model, which means that documents in a collection do not need to have the same fields or data types by default. Once you've established an application schema, you can use schema validation to ensure there are no unintended schema changes or improper data types.

Your schema validation needs depend on how users use your application. When your application is in the early stages of development, schema validation may impose unhelpful restrictions because you don't know how you want to organize your data. Specifically, the fields in your collections may change over time.

Schema validation is most useful for an established application where you have a good sense of how to organize your data.

When MongoDB Checks Validation

  • After you add schema validation rules to a collection:

  • All document inserts must match the rules.

The schema validation level defines how the rules are applied to existing documents and document updates.

Specify JSON Schema Validation

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.

  1. Connect to your MongoDB deployment.
  2. Create a collection with validation.
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"
                }
            }
        }
    }
})

  1. Confirm that the validation prevents invalid documents.
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'
              }
            ]
          }
        ]
      }
    ]
  }
}
  1. Insert a valid document.
// Insert new record
db.students.insertOne( {
  name: "Alice",
  year: NumberInt(2019),
  major: "History",
  gpa: Double(3.0),
  address: {
     city: "NYC",
     street: "33rd Street"
  }
} )

// Query the collection
db.students.find()
[
  {
     "_id": "ObjectId('62bb413014b92d148400f7a5')",
     "name": "Alice",
     "year": 2019,
     "major": "History",
     "gpa": 3,
     "address": { "city": "NYC", "street": "33rd Street" }
  }
]

Refer to the MongoDB Docs for more info

Schema Validation

Specify JSON Schema Validation

Modify Schema Validation