In this lesson, you will learn how to design and query collections that hold different types of documents within the same container, allowing for flexible data modeling.
The Flexibility of Polymorphism
In a traditional relational model, all rows in a table must adhere to the same rigid schema. However, in document databases, we often encounter scenarios where we need to store different entities—like Products, Services, and Subscriptions—inside a single collection. We call this Polymorphic Design.
Instead of creating three separate collections, we store them together and use a "discriminator field" (usually a field like type or category) to identify the document's structure.
Practical Implementation
Imagine a catalog collection. Because a PhysicalProduct needs a weight field, but a DigitalService needs a download_url, we store them like this:
// Document 1
{
"_id": 101,
"type": "physical",
"name": "Mechanical Keyboard",
"weight": "1.2kg"
}
// Document 2
{
"_id": 102,
"type": "service",
"name": "Cloud Storage Upgrade",
"download_url": "https://service.link"
}
By including the type field, the application layer knows exactly how to parse the object. When querying, you simply filter by the discriminator:
-- Conceptual query to retrieve only digital services
SELECT * FROM catalog WHERE type = 'service';
Why Use This Approach?
- Reduced Joins: You can fetch heterogeneous lists (like a user's entire purchase history) in a single read operation without performing complex joins across multiple tables.
- Schema Evolution: You can add new document types to the collection without altering the underlying table structure, which is much safer than modifying a rigid relational schema.
- Application-Level Logic: Since the application knows how to handle the
type, it can dynamically map these documents into specific classes or objects in your code.
While this approach offers great flexibility, keep in mind that you lose strict database-level enforcement of fields. It shifts the responsibility of data integrity to your application logic. Always ensure your application code is prepared to handle the optional fields present in the different variants.
Key Takeaway: Polymorphic documents allow you to group related, yet distinct, data entities into a single collection by using a discriminator field to define their schema at the application level.