0PricingLogin
MongoDB Academy · Lesson

Type, Required, and Enum Constraints

Learners will define type restrictions, mandatory fields, and enumerated allowed values inside a JSON Schema validator.

The Three Core Constraint Types

MongoDB JSON Schema validators support three fundamental constraint categories that cover the majority of real-world validation needs: type constraints that enforce the BSON data type of a field, required constraints that mandate the presence of certain fields, and enum constraints that restrict a field's value to a predefined whitelist. Together they form the backbone of any production schema validator.

BSON Types vs JSON Schema Types

JSON Schema uses standard JSON types like string, number, and object. MongoDB extends this with BSON types declared via the bsonType keyword—values like objectId, date, int, long, double, and decimal. Always use bsonType in MongoDB validators (not type) when you need precision about numeric subtypes or MongoDB-specific types like objectId and date.

// BSON type names to use in validators
// 'string', 'bool', 'int', 'long', 'double', 'decimal',
// 'objectId', 'date', 'array', 'object', 'null', 'binData'

db.createCollection('products', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      properties: {
        _id:       { bsonType: 'objectId' },
        price:     { bsonType: 'decimal' },
        stock:     { bsonType: 'int' },
        isActive:  { bsonType: 'bool' },
        createdAt: { bsonType: 'date' }
      }
    }
  }
});

All lessons in this course

  1. Adding a Validator to a Collection
  2. Type, Required, and Enum Constraints
  3. Validation Levels and Actions
  4. Evolving Schemas Without Downtime
← Back to MongoDB Academy