Zum Inhalt springen
KodeTrail

Camp 1 · Schritt 3 von 12

Documents vs. tables

The same data, modeled twice — see exactly where each approach shines.

12 Min.+50 XPAuf Englisch angezeigt — Übersetzung ist unterwegs

The clearest way to get document databases is to model something twice. Let's store a hiker profile with gear and completed trails — relationally, then as a document.

The relational version

Tables must be flat, so nested things become separate tables joined by keys:

hikers                 gear                    completions
+----+------+         +----+----------+------+  +----------+----------+
| id | name |         | id | hiker_id | item |  | hiker_id | trail    |
+----+------+         +----+----------+------+  +----------+----------+
| 1  | Ada  |         | 1  | 1        | map  |  | 1        | python   |
+----+------+         | 2  | 1        | rope |  | 1        | html     |
                      +----+----------+------+  +----------+----------+

Reading Ada's full profile means joining three tables. Rock-solid, no duplication, great for cross-cutting questions ("which item is owned most?") — at the cost of assembly work for every profile view.

The document version

{
  "_id": 1,
  "name": "Ada",
  "gear": ["map", "rope"],
  "completions": ["python", "html"]
}

One read fetches the entire profile — the shape your app wanted anyway. And the next document may carry different fields entirely (schema flexibility). The cost: asking "who owns a rope?" now scans inside every document, and a trail renamed must be updated in many places.

The honest scorecard

QuestionTablesDocuments
"Show Ada's full profile"joins requiredone read 🏆
"Which gear item is most owned?"one query 🏆harder
Fields differ per recordpainfulnatural 🏆
Update a value used everywhereone place 🏆many places

Neither wins. Access patterns decide: read whole things → documents; slice across things → tables.

Checkpoint

Your app almost always loads a complete user profile (settings, avatar, preferences) in one go. Which model fits naturally?

Checkpoint

What's the real trade-off of embedding everything in one document?