0Pricing
MongoDB Academy · Lesson

The Polymorphic and Schema Versioning Patterns

Learners will design a single collection that holds documents of different shapes using a type discriminator, and version schemas to enable gradual migrations.

Documents With Different Shapes

One of MongoDB's biggest advantages over SQL is that documents in the same collection do not need to share the same fields. This enables the Polymorphic Pattern — storing documents of fundamentally different types in a single collection. Think of a vehicles collection that holds cars, trucks, and motorcycles: all have make and year, but only cars have numberOfDoors and only motorcycles have hasSidecar.

// Polymorphic documents in one 'vehicles' collection
{ _id: ObjectId(), type: 'car',        make: 'Toyota', year: 2022, numberOfDoors: 4, fuelType: 'hybrid' }
{ _id: ObjectId(), type: 'truck',      make: 'Ford',   year: 2021, payloadKg: 1200, hasTrailerHitch: true }
{ _id: ObjectId(), type: 'motorcycle', make: 'Honda',  year: 2023, engineCC: 750, hasSidecar: false }

The Type Discriminator Field

The key to the Polymorphic Pattern is a type discriminator field — a field (commonly named type, kind, or _type) that identifies which subtype a document represents. All application code and indexes can use this field to dispatch behaviour correctly. Index the discriminator field so queries filtering by type execute as IXSCAN rather than COLLSCAN.

// Index the type discriminator
db.vehicles.createIndex({ type: 1 })

// Query only cars
db.vehicles.find({ type: 'car', fuelType: 'hybrid' })

// Query all vehicles regardless of type
db.vehicles.find({ make: 'Toyota' })

All lessons in this course

  1. The Bucket and Computed Patterns
  2. The Extended Reference and Subset Patterns
  3. The Polymorphic and Schema Versioning Patterns
  4. The Outlier and Tree Structure Patterns
← Back to MongoDB Academy