Polymorphic Schemas
Polymorphic Schemas: free step-by-step lesson with examples, common mistakes, and interview tips — part of MongoDB Tutorial on Toolliyo Academy.
On this page
MongoDB Tutorial · Lesson 36 of 100
Polymorphic Schemas
Foundations & CRUD ✓ → Queries & Schema → Aggregation & Scale → Atlas & Projects
Queries & Schema · 2 — Design · ~6 min · MongoDB — Schema Design
What is this?
Polymorphic schemas store different shapes in one collection, often with a type field — like notifications of kinds email, push, and sms sharing createdAt but different payloads.
Why should you care?
One inbox query returns every notification type. Separate collections would force unions in the app for a single feed.
See it live — copy this example
Open mongosh or MongoDB Compass, select database nosqlverse, then run the example. Change one field and run again.
db.events.insertMany([
{ type: "page_view", userId: 1, path: "/courses", at: new Date() },
{ type: "purchase", userId: 1, orderId: ObjectId(), amount: 999, at: new Date() },
{ type: "login", userId: 2, ip: "1.2.3.4", at: new Date() }
])
db.events.find({ type: "purchase", amount: { $gte: 500 } })
db.events.createIndex({ type: 1, at: -1 })
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- All events share type and at, but other fields differ.
- Queries usually filter type first.
- A compound index on type + at supports timelines per event kind.
Practice next
- Insert the three event shapes.
- Query only logins for user 2.
- Add a validator that requires type and at.
- Add type: "quiz_score" with score field.
- Project differently per type in the app layer.
Remember
One collection can hold multiple shapes. Use a discriminator field like type. Index type plus time for feeds.
Activity feed for SaaS
A project tool stores comments, uploads, and status changes in activities with type.
Outcome: One timeline API serves the whole project activity stream.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!