Relational databases give you strong integrity and flexible queries. Document databases give you a flexible schema, fast reads of data stored together, and built-in sharding. Choose by how related your data is and how you query it.
A relational database (like PostgreSQL):
- It stores data in tables with a defined schema (a fixed set of columns and types).
- It enforces relationships with foreign keys and constraints.
- It lets you join and aggregate data in ways you did not plan for.
- Transactions across many rows are normal.
It fits data with many relationships and strong integrity needs, such as orders, payments and inventory.
A document database (like MongoDB):
- It stores self-contained, JSON-like documents with a flexible schema.
- Data that is read together is stored together, so common reads need no joins.
- Sharding (splitting data across many machines) is built in.
The costs:
- Integrity checks are weaker.
- Ad hoc queries across collections are harder.
- You must design documents around your access patterns up front.
For most backends, PostgreSQL is a safe default. Its jsonb column type covers many semi-structured needs. MongoDB makes sense when the data is naturally document-shaped and the access patterns are well known.
- A relational database has a schema, constraints, joins and flexible queries.
- A document database has a flexible schema and stores data by how it is read.
- Document databases offer built-in sharding, while relational databases offer strong integrity.
- Choose by your data relationships and your query patterns.
Read more