Embedding vs referencing decision in MongoDB - Performance Comparison
When choosing between embedding and referencing in MongoDB, it's important to understand how the time to get data changes as your data grows.
We want to know how the way data is stored affects how long queries take when the amount of data increases.
Analyze the time complexity of fetching related data using embedding vs referencing.
// Embedding example
const user = db.users.findOne({ _id: userId });
// user document contains embedded posts array
// Referencing example
const user = db.users.findOne({ _id: userId });
const posts = db.posts.find({ userId: user._id }).toArray();
This code shows two ways to get a user's posts: either embedded inside the user document or stored separately and linked by userId.
Look at what repeats when fetching posts for a user.
- Primary operation: Reading posts data either from embedded array or separate collection.
- How many times: For embedding, posts are read once inside user document. For referencing, a separate query fetches all posts for the user.
Consider how the number of posts (n) affects query time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 posts | Embedding: 1 read including 10 posts; Referencing: 1 user read + 1 query returning 10 posts |
| 100 posts | Embedding: 1 read including 100 posts; Referencing: 1 user read + 1 query returning 100 posts |
| 1000 posts | Embedding: 1 read including 1000 posts; Referencing: 1 user read + 1 query returning 1000 posts |
Pattern observation: Both methods read all posts, but embedding reads them all at once inside one document, while referencing requires a separate query that grows with the number of posts.
Time Complexity: O(n)
This means the time to fetch posts grows linearly with the number of posts, whether embedded or referenced.
[X] Wrong: "Embedding always makes queries faster because all data is in one place."
[OK] Correct: If the embedded data grows very large, reading the whole document can be slow and use more memory. Referencing can be better for very large or frequently changing related data.
Understanding how embedding and referencing affect query time helps you explain design choices clearly and shows you think about how data size impacts performance.
"What if we added an index on the referencing field? How would that change the time complexity of fetching posts?"
Practice
Solution
Step 1: Understand embedding use case
Embedding is best when related data is small and tightly coupled, like a user's addresses.Step 2: Analyze options for embedding
Storing a user's profile and their list of addresses when addresses are few and rarely shared fits because addresses are few and not shared, so embedding improves read speed.Final Answer:
Storing a user's profile and their list of addresses when addresses are few and rarely shared. -> Option AQuick Check:
Embedding = small, tightly related data [OK]
- Embedding large or shared data causing duplication
- Referencing small, simple data unnecessarily
Solution
Step 1: Identify referencing syntax
Referencing stores the related document's ID as a field, usually named with _id suffix.Step 2: Check options for correct ID reference
{ "author_id": ObjectId("507f1f77bcf86cd799439011") } correctly stores the ObjectId with a clear field name author_id.Final Answer:
{ "author_id": ObjectId("507f1f77bcf86cd799439011") } -> Option AQuick Check:
Reference = store related document's ID [OK]
- Using string instead of ObjectId for references
- Using $ref and $id without DBRef context
- Embedding full document instead of referencing
orders where each order embeds a small array of items, what is the expected result of querying an order by ID?Solution
Step 1: Understand embedding query behavior
When data is embedded, querying the parent document returns all embedded data inside it.Step 2: Analyze query result for embedded items
Querying by order ID returns the order document including the embedded items array.Final Answer:
The order document with all embedded items included in the result. -> Option CQuick Check:
Embedding returns full embedded data [OK]
- Expecting separate documents for embedded data
- Thinking embedded arrays cause query errors
- Confusing referencing with embedding results
Solution
Step 1: Identify embedding impact on updates
Embedding large or frequently updated arrays causes the whole document to be rewritten, slowing updates.Step 2: Choose referencing to improve update performance
Referencing posts separately allows updating posts without rewriting the entire user document.Final Answer:
Embedding large arrays causes slow updates; switch to referencing posts separately. -> Option DQuick Check:
Large/frequent updates = use referencing [OK]
- Embedding large arrays despite frequent updates
- Ignoring update performance impact
- Misunderstanding ObjectId role in updates
Solution
Step 1: Analyze comment characteristics
Comments are numerous, large, and updated independently, so embedding would cause large documents and slow updates.Step 2: Choose referencing for scalability and independent updates
Referencing comments in a separate collection allows efficient updates and avoids large blog post documents.Final Answer:
Reference comments in a separate collection linked by post ID. -> Option BQuick Check:
Large, independent data = referencing [OK]
- Embedding large, frequently updated arrays
- Mixing embedding and referencing without clear rules
- Storing JSON strings instead of structured data
Ready to prove it?
Pass the test and this pattern moves unknown
