Polymorphic Pattern
noun
say it: “pol-ee-MOR-fik PAT-ern” /ˌpɑliˈmɔrfɪk ˈpætərn/
A data design that keeps different kinds of records, each with some fields of its own, in one place, with a field saying which kind each one is.
What is the polymorphic pattern?
The polymorphic pattern keeps documents of different shapes in one collection: fields every kind shares, fields only one kind has, and a field such as type that says which kind each is. One query can list them all, and the type picks out one kind.
db.products.insertMany([
{ type: "bike", name: "Trail Runner", price: 899, frameSize: "M" },
{ type: "helmet", name: "Trail Helmet", price: 59, headSize: "56-60 cm" }
]);
db.products.find({ type: "helmet" }); // only the helmets
In a sentence
- “In the polymorphic pattern, only the helmet documents have a headSize field.”
- “Thanks to the polymorphic pattern, the shop's search looks through bikes, helmets and lights in one collection.”
Level: Journeyman · More MongoDB terms at this level
Updated