Documents or Rows? A First Look at Document Databases
If you have learned a little SQL, you think of data as rows in tables. Document databases such as MongoDB store data as documents instead. This post shows the same small example both ways, so you can see what really differs.
The same recipe, two ways
As rows in tables:
recipes ingredients
id | title recipe_id | name | amount
1 | Pancakes 1 | flour | 200 g
1 | milk | 300 ml
1 | eggs | 2
The recipe and its ingredients live in two tables, linked by recipe_id.
As one document:
{
"_id": 1,
"title": "Pancakes",
"ingredients": [
{"name": "flour", "amount": "200 g"},
{"name": "milk", "amount": "300 ml"},
{"name": "eggs", "amount": "2"}
]
}
Everything about the recipe sits together in one nested record, in a collection of similar documents.
What each makes easy
| Task | Rows and tables | Documents |
|---|---|---|
| Show one recipe with its ingredients | A JOIN or two queries | One read |
| Find every recipe that uses milk | A simple query on the ingredients table | Possible, with a query on the nested array |
| Rename "milk" everywhere | One update if ingredients are their own table | Update inside many documents |
| Add an optional field to some recipes | Add a column (often NULL elsewhere) | Just add it to those documents |
| Enforce that every recipe has a title | NOT NULL constraint | Schema validation rules, if you set them up |
The words you will meet
- Document: one record, usually JSON-like, which can contain nested lists and objects.
- Collection: a group of documents, roughly like a table.
- Embedding: putting related data inside the document, like the ingredients above.
- Referencing: storing an id that points to another document, like a foreign key.
Which suits a first project?
For learning how apps talk to databases, I suggest starting with tables and SQL. The ideas of keys, relationships and avoiding repeated data are easier to see there, and they help you design documents well later too. If a course or job uses a document database, the same thinking applies: decide what belongs together, and what is shared and should be referenced instead of copied.
A common misunderstanding
"Schema-less" does not mean "no design". Documents without a planned shape become hard to query: one recipe stores amount as text, another as a number, another forgets it. Many document databases let you add validation rules; using them is wise.
Where to go next
If you want a calm overview of the wider landscape, read a plain guide to relational and NoSQL databases and seven NoSQL words explained. Then try storing a small dataset both ways and writing the same three questions against each. The differences become obvious quickly.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.
Get new pages by email