Skip to content
LESSON 05 / 50Intermediatebson storage

Data Modeling: Embedding vs Referencing (1:1, 1:N, N:N)

The fundamental architectural choice in MongoDB: embedding subdocuments for atomic, single-read access versus referencing documents to avoid duplication and bloat.

Interactive Engine Simulator

BSON Binary Byte Layout Inspector

Explore how MongoDB serializes JSON documents into binary BSON with length headers for O(1) field navigation.

BSON Total Size
61 bytes
Incl. 4B header & 1B \0
Elements Count
4 fields
Type tagged
Field Traversal
O(1) Jump
Via length headers
Max Document Size
16 MB
Hard engine limit
Document Byte Stream (Click to inspect field)
Header:
3d 00 00 00
(4-byte little-endian int32 total length)
0x07"_id":ObjectId (12 bytes)
075f69640065e31f8a3b...(17 B)
0x02"name":UTF-8 String
026e616d65000b000000...(21 B)
0x10"age":32-bit Integer
10616765001d000000(9 B)
0x08"active":Boolean
086163746976650001(9 B)
Terminator:
00
(1-byte null terminator 0x00)
0x07

Field "_id" • ObjectId (12 bytes)

17 Bytes total

ObjectId: 4-byte timestamp, 5-byte random value, 3-byte incrementing counter.

Why BSON over JSON? JSON is text-based and requires full stream parsing ($O(N)$) to find an inner property. BSON embeds length headers for each document and string, letting WiredTiger jump directly to the target byte offset in $O(1)$ time.

1. Formal Definition & Architecture Intent

Embedding stores related data as nested subdocuments or arrays within a single parent document, guaranteeing atomic single-read and single-write performance. Referencing stores related data in separate collections and links them via document IDs, mirroring relational foreign keys.

2. Explain Like I'm 5 (Mental Model)

Embedding is like stapling a receipt directly into your expense report—everything is together in one grab. Referencing is writing down a barcode on the report and keeping the receipt in a separate filing cabinet.

3. Real-World Architecture Example

E-commerce User Profile: Embedding shipping addresses (1:few) vs Referencing historical orders (1:unbounded).

Sample BSON Documents:
Collection: db.users
{
  "_id": "u1",
  "name": "Sarah Connor",
  "addresses": [
    {
      "type": "home",
      "street": "100 Sunset Blvd",
      "city": "LA"
    }
  ]
}
Collection: db.orders
{
  "_id": "o991",
  "user_id": "u1",
  "total": 349.99
}

Addresses are small and bounded, making embedding optimal. Orders grow continuously over years, so embedding them inside the user document would quickly breach the 16MB limit.

4. MQL Implementation Steps

Step 1: Embedded query with dot notation
db.users.find({ "addresses.city": "LA" });
Requires index on "addresses.city" for fast execution.
Step 2: Referenced query using $lookup aggregation stage
db.users.aggregate([
  { $match: { _id: "u1" } },
  {
    $lookup: {
      from: "orders",
      localField: "_id",
      foreignField: "user_id",
      as: "userOrders"
    }
  }
]);
$lookup executes a left-outer join on the referenced collection.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
Embed WhenData is accessed together, relationships are 1:1 or 1:few, and child records are bounded.
Reference WhenData is accessed independently, relationships are 1:unbounded, or child data changes frequently across entities.

6. Deep Dive: Atomicity & Document Relocation Penalties

MongoDB guarantees ACID atomicity at the single-document level. Updating an embedded document is fully atomic without distributed locks. However, in older storage designs or when arrays expand beyond allocated page boundaries, document growth forced physical page reallocations. While WiredTiger handles page reallocations smoothly, excessive document expansion wastes cache space.

// Atomic update on embedded subdocument:
db.users.updateOne(
  { _id: "u1", "addresses.type": "home" },
  { $set: { "addresses.$.street": "500 Ocean Ave" } }
);
Production Warning: Never embed an array that can grow beyond a few hundred elements.

7. Architectural Trade-offs

Advantages
  • •Embedding eliminates expensive $lookup joins and delivers ultra-fast single disk read access
  • •Atomic updates across related data without requiring multi-document distributed transactions
  • •Referencing keeps documents lean, avoiding 16MB document size ceiling
Disadvantages & Gotchas
  • •Embedding causes data redundancy when child entities are shared across multiple parents
  • •Referencing requires application-level joins or server-side $lookup aggregation overhead

8. Technical Interview Questions

Q1: When should you NEVER embed an array of subdocuments in MongoDB?

You should never embed an array when the cardinality is 1:unbounded (e.g. user activity logs, product reviews, IoT sensor ticks). Unbounded arrays will inevitably breach the 16MB document limit, degrade WiredTiger cache locality, and slow down document updates.

9. Staff-Level Ready Answer

"The decision between embedding and referencing is governed by data cardinality and access patterns. Embed for 1:1 or 1:few relationships that are queried together and strictly bounded. Reference for 1:unbounded relationships or entities that are updated independently to avoid 16MB document exhaustion."

10. Quick Knowledge Check

A blogging platform has Users, Posts, and Comments. Which modeling strategy is optimal for Comments on high-traffic posts?