Software Development

Should I use Embedding or Referencing for one-to-many relationships in MongoDB?

AM Asked by Amanda Foster · 14-06-2025
0 upvotes 12,149 views 0 comments
The question

I’m designing a blogging platform and I’m stuck on how to handle comments. Should I embed the comments directly into the post document, or should I reference them by storing comment IDs and keeping the actual text in a separate collection? I’m worried about hitting the 16MB document size limit if a post goes viral and gets thousands of comments.

3 answers

0
DE
Answered on 19-06-2025

This is the classic "One-to-N" dilemma. In 2023, I worked on a social app where we initially embedded everything. We hit that 16MB BSON limit faster than expected! For comments, I recommend a hybrid approach or "Bucketing." If you expect thousands of entries, referencing is safer. However, if you only expect 50-100 items, embedding is faster because it’s a single IO operation. For a blog, I’d suggest storing the most recent 10 comments in the post document and moving the rest to a separate collection to keep the main document lean and fast.

0
KE
Answered on 21-06-2025

Have you looked into the "Extended Reference" pattern? It allows you to keep the essential data for display embedded while keeping the bulk of the information in a separate collection to save space.

AM 23-06-2025

Kevin, I haven't tried the Extended Reference pattern yet, but it sounds like exactly what I need. I could store the user's name and the comment summary in the post document, then link to the full thread. This would allow the main feed to load instantly without pulling in megabytes of text for every single post. Thanks for the tip, I'm going to look up the implementation details in the MongoDB documentation today.

0
BR
Answered on 25-06-2025

Always default to referencing if you have an "unbounded" relationship. Breaking the 16MB limit will crash your application's read/write operations completely.

DE 28-06-2025

Brian makes a vital point. The 16MB limit is a hard stop. It’s better to have a slightly slower query with a reference than a broken app with a bloated document.

Share your thoughts

Your email address will not be published. Required fields are marked (*)

Professional Counselling Session

Still have questions?
Schedule a free counselling session

Our experts are ready to help you with any questions about courses, admissions, or career paths. Get personalized guidance from industry professionals.

Request a Call Back

Search Online

We Accept

We Accept

Follow Us

"PMI®", "PMBOK®", "PMP®", "CAPM®" and "PMI-ACP®" are registered marks of the Project Management Institute, Inc. | "CSM", "CST" are Registered Trade Marks of The Scrum Alliance, USA. | COBIT® is a trademark of ISACA® registered in the United States and other countries.

Book Free Session