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.

Database performance basics illustration

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

TaskRows and tablesDocuments
Show one recipe with its ingredientsA JOIN or two queriesOne read
Find every recipe that uses milkA simple query on the ingredients tablePossible, with a query on the nested array
Rename "milk" everywhereOne update if ingredients are their own tableUpdate inside many documents
Add an optional field to some recipesAdd a column (often NULL elsewhere)Just add it to those documents
Enforce that every recipe has a titleNOT NULL constraintSchema validation rules, if you set them up

The words you will meet

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

Related pages on this site