The choice between embedding and referencing is a recurring dilemma in MongoDB design.
If you decide the wrong way, you’ll either hit the 16 MB limit, suffer slow writes, or pay the cost of an extra round‑trip for every read.
TL;DR
- Embed when the child data is small, read‑heavy, and changes only with its parent.
- Reference when the child collection can grow large, updates are independent, or you need to query children separately.
- Hybrid gives the best of both worlds: recent comments embedded, older ones referenced.
- Always index the foreign key in the referenced model and be mindful of the 16 MB document ceiling.
The Decision Dilemma: When to Embed or Reference
Identify the primary access pattern
If the application almost always fetches a post along with its comments, embedding is attractive because a single findOne returns everything.
When comments are queried on their own (e.g., a moderation dashboard that lists recent comments across all posts), referencing shines.
Consider data duplication cost and the likelihood of changes
Duplicating a comment in every post that references it is wasteful.
If a comment’s text changes, you must update every parent document that contains it.
When the nested data is immutable (like a user’s profile embedded in a session log), duplication is acceptable.
Evaluate how often the parent and child data will be updated together
If the parent and child are always updated together (e.g., a post and its metadata), embedding reduces the number of write operations.
If a child can be updated independently (e.g., a comment’s “likes” count changes while the post remains unchanged), referencing keeps writes isolated.
Embedding in Action: Storing Comments Inside Posts
Schema example
const commentSchema = new mongoose.Schema({
author: String,
body: String,
createdAt: { type: Date, default: Date.now }
});
const postSchema = new mongoose.Schema({
title: String,
body: String,
comments: [commentSchema] // <‑‑ embedded array
});
const Post = mongoose.model('Post', postSchema);
Create operation
const newPost = await Post.create({
title: 'First Post',
body: 'Hello World',
comments: [
{ author: 'Alice', body: 'Nice post!' },
{ author: 'Bob', body: 'Thanks for sharing.' }
]
});
Read operation
const post = await Post.findOne({ title: 'First Post' }).lean();
console.log(post.comments); // all comments returned in the same document
Explanation
The comments field is an array of sub‑documents stored inline. A single query retrieves the entire post, including every comment.
Writes that append a new comment modify the parent document’s array, which is efficient when the array stays small.
Referencing in Action: Linking Comments to Posts
Schema example
const commentSchema = new mongoose.Schema({
postId: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' },
author: String,
body: String,
createdAt: { type: Date, default: Date.now }
});
const postSchema = new mongoose.Schema({
title: String,
body: String
});
const Post = mongoose.model('Post', postSchema);
const Comment = mongoose.model('Comment', commentSchema);
Create operation
const post = await Post.create({ title: 'First Post', body: 'Hello World' });
await Comment.create({
postId: post._id,
author: 'Alice',
body: 'Nice post!'
});
Read operation
// Option 1: manual two‑step fetch
const post = await Post.findOne({ title: 'First Post' }).lean();
const comments = await Comment.find({ postId: post._id }).lean();
// Option 2: populate (adds an extra round‑trip internally)
const postWithComments = await Post.findOne({ title: 'First Post' })
.populate('comments')
.lean();
Explanation
Each comment lives in its own document. The postId field is indexed for quick lookup.
Fetching a post and its comments requires an additional query or an aggregation pipeline.
This pattern scales to thousands of comments per post without hitting the document size limit.
Hybrid Strategy: Combining Embedding and Referencing
Many real‑world blogs store only the most recent comments embedded for a snappy “view post” experience, while older comments are archived in a separate collection.
const recentCommentSchema = new mongoose.Schema({
author: String,
body: String,
createdAt: { type: Date, default: Date.now }
});
const postSchema = new mongoose.Schema({
title: String,
body: String,
recentComments: [recentCommentSchema] // capped to, say, 20
});
const oldCommentSchema = new mongoose.Schema({
postId: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' },
author: String,
body: String,
createdAt: { type: Date, default: Date.now }
});
When a new comment arrives, insert it into the recentComments array.
If the array exceeds the cap, shift the oldest comment into the OldComment collection and remove it from the array.
Reads of a post show the latest comments instantly; moderators can query the old comments collection for deep archives.
Performance & Indexing Considerations
Write throughput
- Embedding: One write operation for the parent document. Write speed drops sharply as the array grows because MongoDB must rewrite the entire document.
- Referencing: Each comment is a separate write, so the parent document remains unchanged. This is preferable when comments arrive at a high rate.
Indexing
- In the referenced model, create an index on
postId({ postId: 1 }). - In the embedded model, you can’t index individual comments; you’re limited to indexing the parent document’s fields.
- In the referenced model, create an index on
Aggregations
- Unwinding large embedded arrays can be memory‑intensive.
- Aggregations on referenced collections benefit from the database’s ability to index and stream results.
Document size limit
- MongoDB enforces a 16 MB cap per document.
- Even if comments are short, a very active thread can quickly exceed this limit, forcing a switch to referencing or a hybrid approach.
Common Mistakes & Trade‑Offs
| Mistake | Why it hurts | Mitigation |
|---|---|---|
| Over‑embedding tiny collections | Increases storage and duplicate writes, but you lose the ability to query the child collection directly. | Only embed when the child data is read‑heavy and rarely queried alone. |
| Ignoring referential integrity | Deleting a post without cascading deletes leaves orphaned comments that consume space and pollute analytics. | Use Mongoose middleware (pre('remove')) or database triggers to clean up. |
| Blowing the 16 MB limit | Write errors or data loss when a document grows too large. | Monitor document sizes; switch to referencing or hybrid when nearing the cap. |
| Choosing based on current size only | A small comment thread today may grow rapidly; embedding now could become a bottleneck later. | Forecast growth; consider a hybrid or reference strategy early. |
| Neglecting index design | Unindexed foreign keys slow down comment lookups, turning a cheap read into a full scan. | Index postId in the comment collection; index frequently queried fields in the parent. |
Key takeaways
- Embed when the child collection is small, changes only with the parent, and you need fast single‑document reads.
- Reference when the child can grow large, updates are independent, or you need to query children separately.
- Hybrid patterns (recent comments embedded, older ones referenced) balance read performance with scalability.
- Always index foreign keys, monitor document size, and plan for growth to avoid costly migrations later.
FAQ
When should I embed child documents in MongoDB?
Embed when the child data is small, read‑heavy, and changes only with its parent. This allows a single findOne to return all data without extra round‑trips.
What are the downsides of embedding too many comments?
Embedding many comments can quickly approach MongoDB’s 16 MB document size limit and cause writes to become slower because the entire document must be rewritten.
How do I index a referenced child collection?
Create an index on the foreign key field, e.g., `db.comments.createIndex({ postId: 1 })`, to enable fast lookups when populating or querying by post.
Can I use a hybrid approach?
Yes, store recent comments embedded for fast reads and move older comments to a separate collection, shifting them when the embedded array exceeds a chosen cap.