Loading

Quipoin Menu

Learn • Practice • Grow

mongodb / Data Modeling Embedding vs Referencing
interview

Q1. What is embedding in MongoDB data modeling?
Embedding means storing related data within a single document as nested objects or arrays. For example, a blog post document might embed comments:
{ title: "Post", comments: [ { text: "Great", author: "John" } ] }
Embedding is good for one-to-few relationships and when data is accessed together.

Q2. What is referencing in MongoDB?
Referencing stores relationships by including a reference (usually _id) to another document. For example, a product document might reference a category:
{ name: "Laptop", categoryId: ObjectId("...") }
This is like foreign keys in SQL and is used for one-to-many or many-to-many relationships.

Q3. When should you use embedding vs referencing?
Use embedding when: - Data is always accessed together (e.g., order and order items) - There is a one-to-few relationship - Data doesn't grow indefinitely Use referencing when: - Data grows unbounded (e.g., comments on a popular post) - You need to update related data independently - Many-to-many relationships

Q4. How do you handle one-to-many relationships?
You can either embed the many side as an array if it's small, or reference them. For example, a blog post with comments: if comments are limited, embed them. If comments can be thousands, store comments in a separate collection and reference the postId in each comment.

Q5. What is the 16MB document size limit and how does it affect modeling?
Each MongoDB document has a 16MB size limit. This means embedding large arrays or nested structures can hit this limit. For scenarios with large or unbounded data, referencing is necessary. For example, storing all chat messages in a user document would quickly exceed 16MB, so they should be referenced.