MongoDB Polymorphic Associations
MongoDB Polymorphic Associations
MongoDB Polymorphic Associations
Tip: Type Field
$comment = [
'body' => 'Great post!',
'commentable_type' => 'post',
'commentable_id' => $postId,
];
Gotcha: No Foreign Keys
MongoDB doesn't enforce referential integrity. Orphaned references are possible.
Tip: Query by Type
$collection->find(['commentable_type' => 'post', 'commentable_id' => $postId]);
Gotcha: Index on Type + ID
$collection->createIndex(['commentable_type' => 1, 'commentable_id' => 1]);
Tip: Embedded vs Referenced
For one-to-few, embed comments in the parent document. For many, use references.
Gotcha: Schema Validation
Add validation for commentable_type to prevent typos.
Tip: Embed or Reference? The 80/20 Rule
If you always access data together, embed it. If you access it independently, reference it. The 16MB document size limit is the hard boundary — stay under 1MB for most documents.
Tip: Index Your Query Patterns, Not All Fields
Creating indexes on every field wastes RAM. Use explain() to find in-memory sorts and collection scans. Index only what your actual queries filter on.
Gotcha: No Transaction Rollback for Index Builds
Building an index on a large collection can take hours. If it fails midway, the partial index is silently discarded. Plan index builds during maintenance windows.
Senior Insight
Polymorphic associations in MongoDB are natural — just store a type field alongside the reference. I've used this pattern for comments that can belong to posts, articles, or videos. The query pattern: find({refType: 'post', refId: postId}). The index strategy: a compound index on (refType, refId) makes these lookups efficient. This is one area where MongoDB's schema flexibility genuinely simplifies a pattern that's awkward in relational databases.
Source: MongoDB Developer Center (https://www.mongodb.com/developer/), MongoDB Engineering Blog (https://www.mongodb.com/blog/channel/engineering-blog), Studio 3T Blog (https://studio3t.com/blog/)