Database Document Databases
What you will learn
- What a document and a collection are
- Why document shapes may differ from one record to the next
- How to query inside documents
- When documents fit better than tables, and when they do not
About the examples in this lesson. The Python code below is a small model of the idea, built from plain Python data (dictionaries, lists, JSON text) so you can run it in your browser. It is not a real database product. Real products of this kind are separate programs, usually run on a server, with many more features. This course does not run them; it teaches the idea so that you can recognise the kind and choose well.
1. Documents
A document database stores each record as one self-contained document, usually JSON-like: named fields, nested objects and lists. Documents of one kind are grouped in a collection, which is roughly a table. Products such as MongoDB work this way: MongoDB stores its documents in BSON, a binary form of JSON that has more data types (checked in its documentation). A course on MongoDB comes later.
Here is a collection as plain Python data. Notice that the three documents do not have the same fields:
docs = [
{"id": 1, "name": "Rina", "phones": ["0171", "0181"], "address": {"city": "Dhaka"}},
{"id": 2, "name": "Sam", "email": "sam@example.com"},
{"id": 3, "name": "Lee", "address": {"city": "Dhaka", "area": "Mirpur"}},
]
print([d["name"] for d in docs if d.get("address", {}).get("city") == "Dhaka"])
print([len(d.get("phones", [])) for d in docs])
['Rina', 'Lee']
[2, 0, 0]
Rina has two phones and a nested address, Sam has an email and no address, Lee has an extra area. In a table you would need columns for all of these, many of them NULL, or extra tables for the phones.
2. Documents inside a relational database
You can try the idea in SQLite, which can store JSON as text and look inside it:
import json, sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE docs (id INTEGER PRIMARY KEY, body TEXT)")
for d in docs:
con.execute("INSERT INTO docs VALUES (?, ?)", (d["id"], json.dumps(d)))
print(con.execute("SELECT json_extract(body, '$.name') FROM docs WHERE json_extract(body, '$.address.city') = 'Dhaka' ORDER BY id").fetchall())
print(con.execute("SELECT body FROM docs WHERE id = 2").fetchone()[0])
[('Rina',), ('Lee',)]
{"id": 2, "name": "Sam", "email": "sam@example.com"}
The whole document comes back in one read. That is the main attraction: data that is read together is stored together.
3. Trade-offs
| Documents are good when | Tables are better when |
|---|---|
| the shape varies between records | every record has the same fields |
| a record is nearly always read whole (a profile, a product page) | you must combine data from many kinds of record |
| the data nests naturally (an order with its lines) | the same fact is shared by many records (a customer used in many orders) |
The cost is repeated data. If each order document holds a copy of the customer's address, changing the address means updating many documents, the same problem normalization solved in chapter 5. Documents also usually give fewer built-in rules and weaker joins, though the details depend on the product.
Worked example: a product catalogue
A shop sells shirts (size, colour), books (author, pages) and phones (memory, battery). Each product kind has different fields, and a product page shows all of one product at once. One document per product fits well. The orders and payments of the same shop still fit tables better, because they must stay exact and linked. Many real systems use both.
The shop is made up.
Common mistakes
- Thinking "no fixed shape" means "no design". The application still expects certain fields; the rules just live in the code.
- Copying shared data into many documents and then letting the copies drift apart.
- Choosing documents only because tables feel hard. Data with many links is easier to keep correct in tables.
Key takeaways
- A document database stores self-contained JSON-like records in collections.
- Shapes can differ between documents, and related data can be nested together.
- It suits data read as a whole; it struggles when many records share the same facts.
- Real systems often combine documents and tables.
Practice
1. What is a collection?
Show answer
A group of documents of one kind, roughly the equivalent of a table.
2. In the demo, which document has no phones, and what did d.get("phones", []) return for it?
Show answer
Sam's (and Lee's). get returned the default empty list, so the length was 0.
3. Why is repeated data a risk in documents?
Show answer
A change must be made in every copy; missing one leaves the data inconsistent.
4. Give a kind of data that suits documents.
Show answer
For example product pages with different fields per product kind, or user profiles with optional parts.
5. What does json_extract(body, '$.address.city') do?
Show answer
It reads the city value inside the address object of the JSON text in body.
6. A shop stores each order as one document that contains a copy of the customer's name and address. A customer moves house. What goes wrong, and what would a relational design do instead?
Show answer
Old orders keep the old address, and if the current address is wanted, every document that copied it must be found and changed; missing one leaves the data inconsistent. (If an order should keep the address it was shipped to, the copy is correct, so decide which you mean.) A relational design stores the address once in customers and links orders to it by a foreign key, and keeps a separate shipping address on the order when that must not change.