Bird
Raised Fist0
MongoDBquery~10 mins

Embedding vs referencing decision in MongoDB - Visual Side-by-Side Comparison

Choose your learning style10 modes available
Concept Flow - Embedding vs referencing decision
Start: Need to model related data
↓
Decide: Embed or Reference?
↓
Embed if data is
↓
small, tightly
↓
related, rarely
↓
changed together
↓
Implement chosen data model
↓
Query and update data accordingly
This flow shows how to decide between embedding or referencing data in MongoDB based on data size, relation, and update frequency.
Execution Sample
MongoDB
db.users.insertOne({
  name: "Alice",
  address: { city: "NY", zip: "10001" }
})

// vs

db.users.insertOne({ name: "Bob", address_id: ObjectId("abc123") })
db.addresses.insertOne({ _id: ObjectId("abc123"), city: "LA", zip: "90001" })
Shows embedding address inside user vs referencing address by ID.
Execution Table
StepActionData ModelData StoredQuery Impact
1Insert user with embedded addressEmbedding{name: 'Alice', address: {city: 'NY', zip: '10001'}}Single query to get user and address
2Insert user with referenced addressReferencing{name: 'Bob', address_id: ObjectId('abc123')}, {_id: ObjectId('abc123'), city: 'LA', zip: '90001'}Two queries or $lookup needed to get full data
3Update embedded address cityEmbeddingUpdate user document directlySimple update, no joins
4Update referenced address cityReferencingUpdate address document separatelySeparate update, user document unchanged
5Query user with embedded addressEmbeddingOne document returned with all dataFast, no joins
6Query user with referenced addressReferencingUser document returned, address fetched separatelySlower, needs join or multiple queries
7ExitDecision endsChoose embedding for small, tightly coupled data Choose referencing for large, shared, or frequently changing dataDecision based on data characteristics
💡 Decision stops after evaluating data size, relation, and update patterns
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
User Document{}{name: 'Alice', address: {city: 'NY', zip: '10001'}}{name: 'Alice', address: {city: 'NY', zip: '10001'}}{name: 'Alice', address: {city: 'NY', zip: '10001'}}{name: 'Alice', address: {city: 'NY', zip: '10001'}}Embedded address inside user
Address Document{}N/AN/AN/A{_id: ObjectId('abc123'), city: 'LA', zip: '90001'}{_id: ObjectId('abc123'), city: 'LA', zip: '90001'}
User Document with Reference{}N/A{name: 'Bob', address_id: ObjectId('abc123')}{name: 'Bob', address_id: ObjectId('abc123')}{name: 'Bob', address_id: ObjectId('abc123')}User references address by ID
Key Moments - 3 Insights
Why do we embed data sometimes instead of referencing?
Embedding is chosen when related data is small, changes together, and is accessed together, so one document holds all needed info (see execution_table rows 1, 5).
When is referencing better than embedding?
Referencing is better when related data is large, shared by many documents, or changes independently, requiring separate updates (see execution_table rows 2, 4, 6).
Does embedding always mean faster queries?
Usually yes, because all data is in one document (row 5), but if embedded data grows too large, it can slow writes or exceed document size limits.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step is the user document updated directly with address data?
AStep 3
BStep 2
CStep 4
DStep 6
💡 Hint
Check the 'Action' and 'Data Model' columns for direct updates to embedded data.
According to variable_tracker, what does the user document contain after Step 2?
AEmbedded address object
BEmpty document
CReference to address by ID
DSeparate address document
💡 Hint
Look at 'User Document with Reference' row after Step 2.
If the address data changes frequently and is shared by many users, which data model is better according to the execution flow?
AEmbedding
BReferencing
CNeither
DBoth equally
💡 Hint
Refer to concept_flow and key_moments about data change frequency and sharing.
Concept Snapshot
Embedding vs Referencing in MongoDB:
- Embed when related data is small, accessed and updated together.
- Reference when data is large, shared, or changes independently.
- Embedding stores data in one document; referencing uses IDs to link documents.
- Embedding simplifies queries; referencing supports data reuse and separate updates.
- Choose based on data size, relation, and update patterns.
Full Transcript
This visual execution shows how to decide between embedding and referencing data in MongoDB. First, you consider if the related data is small and tightly connected, or large and loosely connected. Embedding means putting related data inside one document, which makes queries faster and updates simpler when data changes together. Referencing means storing related data in separate documents and linking them by IDs, which is better when data is large, shared by many, or changes independently. The execution table traces inserting users with embedded or referenced addresses, updating them, and querying them. The variable tracker shows how user and address documents change step by step. Key moments clarify why embedding is chosen for small, tightly coupled data and referencing for large, shared data. The quiz tests understanding of these steps and decisions. The quick snapshot summarizes when to embed or reference and their effects on queries and updates.

Practice

(1/5)
1. Which scenario is best suited for embedding related data in MongoDB?
easy
A. Storing a user's profile and their list of addresses when addresses are few and rarely shared.
B. Storing product details and linking to multiple categories by ID.
C. Storing large documents that are frequently updated independently.
D. Storing shared tags used by many blog posts.

Solution

  1. Step 1: Understand embedding use case

    Embedding is best when related data is small and tightly coupled, like a user's addresses.
  2. 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.
  3. Final Answer:

    Storing a user's profile and their list of addresses when addresses are few and rarely shared. -> Option A
  4. Quick Check:

    Embedding = small, tightly related data [OK]
Hint: Embed when data is small and tightly linked [OK]
Common Mistakes:
  • Embedding large or shared data causing duplication
  • Referencing small, simple data unnecessarily
2. Which of the following is the correct way to reference a document in MongoDB?
easy
A. { "author_id": ObjectId("507f1f77bcf86cd799439011") }
B. { "author": { "$ref": "users", "$id": ObjectId("507f1f77bcf86cd799439011") } }
C. { "author": ObjectId("507f1f77bcf86cd799439011") }
D. { "author": "507f1f77bcf86cd799439011" }

Solution

  1. Step 1: Identify referencing syntax

    Referencing stores the related document's ID as a field, usually named with _id suffix.
  2. Step 2: Check options for correct ID reference

    { "author_id": ObjectId("507f1f77bcf86cd799439011") } correctly stores the ObjectId with a clear field name author_id.
  3. Final Answer:

    { "author_id": ObjectId("507f1f77bcf86cd799439011") } -> Option A
  4. Quick Check:

    Reference = store related document's ID [OK]
Hint: Reference by storing ObjectId in a field ending with _id [OK]
Common Mistakes:
  • Using string instead of ObjectId for references
  • Using $ref and $id without DBRef context
  • Embedding full document instead of referencing
3. Given a MongoDB collection orders where each order embeds a small array of items, what is the expected result of querying an order by ID?
medium
A. Only the order document without any items data.
B. An error because embedded arrays cannot be queried.
C. The order document with all embedded items included in the result.
D. A list of item documents from a separate collection.

Solution

  1. Step 1: Understand embedding query behavior

    When data is embedded, querying the parent document returns all embedded data inside it.
  2. Step 2: Analyze query result for embedded items

    Querying by order ID returns the order document including the embedded items array.
  3. Final Answer:

    The order document with all embedded items included in the result. -> Option C
  4. Quick Check:

    Embedding returns full embedded data [OK]
Hint: Embedded data returns inside parent document query [OK]
Common Mistakes:
  • Expecting separate documents for embedded data
  • Thinking embedded arrays cause query errors
  • Confusing referencing with embedding results
4. You have a MongoDB schema where user documents embed an array of posts. You notice performance issues when updating posts frequently. What is the likely cause and fix?
medium
A. Indexing embedded arrays causes slow updates; remove indexes.
B. Referencing posts causes slow updates; embed posts instead.
C. Using ObjectId for posts causes slow updates; use strings instead.
D. Embedding large arrays causes slow updates; switch to referencing posts separately.

Solution

  1. Step 1: Identify embedding impact on updates

    Embedding large or frequently updated arrays causes the whole document to be rewritten, slowing updates.
  2. Step 2: Choose referencing to improve update performance

    Referencing posts separately allows updating posts without rewriting the entire user document.
  3. Final Answer:

    Embedding large arrays causes slow updates; switch to referencing posts separately. -> Option D
  4. Quick Check:

    Large/frequent updates = use referencing [OK]
Hint: Large, frequently updated data? Use referencing [OK]
Common Mistakes:
  • Embedding large arrays despite frequent updates
  • Ignoring update performance impact
  • Misunderstanding ObjectId role in updates
5. You are designing a MongoDB schema for a blogging platform. Each blog post has many comments, and comments can be edited or deleted independently. Also, comments can be very large in number. What is the best design choice?
hard
A. Embed all comments inside each blog post document.
B. Reference comments in a separate collection linked by post ID.
C. Embed only the first 10 comments and reference the rest.
D. Store comments as a JSON string inside the blog post.

Solution

  1. Step 1: Analyze comment characteristics

    Comments are numerous, large, and updated independently, so embedding would cause large documents and slow updates.
  2. Step 2: Choose referencing for scalability and independent updates

    Referencing comments in a separate collection allows efficient updates and avoids large blog post documents.
  3. Final Answer:

    Reference comments in a separate collection linked by post ID. -> Option B
  4. Quick Check:

    Large, independent data = referencing [OK]
Hint: Large, independent data? Reference separately [OK]
Common Mistakes:
  • Embedding large, frequently updated arrays
  • Mixing embedding and referencing without clear rules
  • Storing JSON strings instead of structured data
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard