MySQL vs MongoDB: Key Differences, Decision Table and Data Models
For the developer or architect picking the database for a new service, who writes SQL and has read a document model without having designed one.
On this page
You're starting a new service and have to decide whether its data goes into MySQL tables or MongoDB documents. Choose MySQL when one write has to change several records and keep them consistent: InnoDB checks foreign keys on every write and runs transactions on a single server. Choose MongoDB when the service mostly reads one parent together with its children: they can live in one document and come back in one read.
Every statement below ran on MySQL 9.1 and MongoDB 8.2 with the data in that picture: France and two of its cities. Each result and error is copied from the run. The MySQL behavior matches the MySQL 9.7 manual, and the MongoDB behavior the current MongoDB manual.
Key differences between MySQL tables and MongoDB documents
The difference that produces all the others is the unit of storage. MySQL stores a row in a table whose columns are declared in advance, so the names and types are written once, in the table, and every row has them. MongoDB stores a document in a collection, and each document carries its own field names and types, so two documents in one collection can hold different fields.
So the same change behaves differently on each side. Adding a field in MongoDB means writing it on the next insert, and the documents already stored keep their old shape until something rewrites them. Adding a column in MySQL is an ALTER TABLE that gives every existing row the column at once, and from then on the server refuses a write that doesn't fit.
| Criterion | MySQL | MongoDB |
|---|---|---|
| Unit of storage | Row in a table | BSON document in a collection |
| Query language | SQL | MongoDB Query API and aggregation pipeline |
| Schema enforcement | Every write, by the table definition | Only with a validator on the collection |
| Join between tables or collections | SQL JOIN | $lookup, within one database |
| One-to-one | Child table, UNIQUE foreign key | Embedded document |
| One-to-many | Foreign key column in the child table | Embedded array, or a reference |
| Transaction over several records | Works on a single server | Replica set or sharded cluster only |
| Adding a field | ALTER TABLE, instant by default | Written on the next insert |
| Reading one parent with its children | A join at read time | One document read |
| One table or collection across servers | Not with InnoDB; a replica holds a full copy | Sharded cluster, split by shard key |
| Limit to watch | 255 instant column changes per table | 16 MiB per document |
The sections below demonstrate every row that needs it, except scaling. MongoDB sharding splits one collection across several servers by a shard key, and routes each query to the shards that hold its documents. An InnoDB table lives on one server, and a MySQL replica receives every change to it, which spreads the reads but not the data. If you expect one collection to outgrow a single server, that row counts toward MongoDB.
Relational modeling with a MySQL example
MySQL wants the structure first: the tables, their columns and types, and the foreign keys, all declared before the first row goes in.
CREATE TABLE countries (
id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
population INT
);
CREATE TABLE cities (
id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
population INT,
country_id INT NOT NULL,
FOREIGN KEY (country_id) REFERENCES countries (id)
);
INSERT INTO countries VALUES (1, 'France', 68000000);
INSERT INTO cities VALUES (101, 'Paris', 2100000, 1), (102, 'Lyon', 520000, 1);
From here the server holds every write to that structure. It refuses a city whose country doesn't exist:
INSERT INTO cities VALUES (103, 'Atlantis', 0, 99);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`geo`.`cities`, CONSTRAINT `cities_ibfk_1` FOREIGN KEY (`country_id`) REFERENCES `countries` (`id`))
It refuses a misspelled column too, because the table defines which columns exist:
INSERT INTO cities (id, name, popluation, country_id) VALUES (104, 'Nice', 350000, 1);
ERROR 1054 (42S22): Unknown column 'popluation' in 'field list'
Reading a country with its cities takes a join. MySQL created an index on the foreign key column when you declared the constraint, so the join is indexed without further work.
SELECT co.name AS country, ci.name AS city, ci.population
FROM countries co
JOIN cities ci ON ci.country_id = co.id
ORDER BY ci.population DESC;
| country | city | population |
|---|---|---|
| France | Paris | 2100000 |
| France | Lyon | 520000 |
Changing the structure later is cheap for a new column and expensive for a new type. ADD COLUMN and DROP COLUMN default to ALGORITHM=INSTANT and change only the table's metadata, up to 255 row versions per table. A new column type rebuilds the table, and MySQL says so when you ask for it instantly:
ALTER TABLE cities ADD COLUMN area_km2 INT, ALGORITHM=INSTANT;
ALTER TABLE cities MODIFY population BIGINT, ALGORITHM=INSTANT;
The first statement succeeds, and the second is refused:
ERROR 1846 (0A000): ALGORITHM=INSTANT is not supported. Reason: Need to rebuild the table to change column type. Try ALGORITHM=COPY/INPLACE.
Document modeling with a MongoDB example
MongoDB has no statement that declares the shape of a collection. You insert a document, and the document is the shape. You can store the countries and cities in two ways, and that choice is the main design decision on this side.
Embedded documents
Embedding puts the cities inside the country document, as an array:
db.countries.insertOne({
_id: 1,
name: "France",
population: 68000000,
cities: [
{ name: "Paris", population: 2100000 },
{ name: "Lyon", population: 520000 }
]
})
db.countries.findOne({ _id: 1 })
The one read returns the country and its cities together:
{
"_id": 1,
"name": "France",
"population": 68000000,
"cities": [
{ "name": "Paris", "population": 2100000 },
{ "name": "Lyon", "population": 520000 }
]
}
Embed when the cities are read with their country, are seldom queried on their own, and the array has a ceiling. An array that keeps growing eventually reaches the 16 MiB document limit.
Referenced collections
Referencing keeps the cities in a collection of their own, each holding the _id of its country, as the MySQL tables do:
db.countries.insertOne({ _id: 1, name: "France", population: 68000000 })
db.cities.insertMany([
{ _id: 101, name: "Paris", population: 2100000, country_id: 1 },
{ _id: 102, name: "Lyon", population: 520000, country_id: 1 }
])
The two inserts that MySQL refused both succeed here. Nothing tells MongoDB that country_id points at a country, or that the field is called population:
db.cities.insertOne({ _id: 103, name: "Atlantis", population: 0, country_id: 99 })
db.cities.insertOne({ _id: 104, name: "Nice", popluation: 350000, country_id: 1 })
{ acknowledged: true, insertedId: 103 }
{ acknowledged: true, insertedId: 104 }
Reading a country with its cities now takes a second query, or a $lookup stage, which joins to a collection in the same database:
db.countries.aggregate([
{ $match: { _id: 1 } },
{ $lookup: { from: "cities", localField: "_id", foreignField: "country_id", as: "cities" } },
{ $project: { name: 1, "cities.name": 1 } }
])
Nice comes back like any other city, and nothing in the result points at the misspelled field or at Atlantis, which belongs to no country:
[
{
"_id": 1,
"name": "France",
"cities": [ { "name": "Paris" }, { "name": "Lyon" }, { "name": "Nice" } ]
}
]
Reference when the child side grows without a ceiling, is written at different times from the parent, or is queried on its own. Your application then makes the checks that the foreign key made in MySQL.
Embed or reference a one-to-one relationship
With one child per parent there's no array to grow, so embed a one-to-one child unless one of the cases below applies. MongoDB's guidance is to shape the document so that the application gets what it needs in a single read. Embedding the child is one $set on the parent:
db.countries.updateOne(
{ _id: 1 },
{ $set: { capital: { name: "Paris", population: 2100000 } } }
)
France's document now holds its capital. A separate collection is worth the extra query in three cases. The child is read without the parent, such as a profile page that never shows the account it belongs to. The child is updated far more often than the parent, so each of those updates touches the parent's document. Or the child is large enough to push the parent toward the document limit.
MySQL states one-to-one as a child table whose foreign key is also UNIQUE. The UNIQUE is what stops a country from getting a second capital:
CREATE TABLE capitals (
country_id INT NOT NULL UNIQUE,
city_id INT NOT NULL,
FOREIGN KEY (country_id) REFERENCES countries (id),
FOREIGN KEY (city_id) REFERENCES cities (id)
);
INSERT INTO capitals VALUES (1, 101);
INSERT INTO capitals VALUES (1, 102);
ERROR 1062 (23000): Duplicate entry '1' for key 'capitals.country_id'
The read then costs a join every time, which is the price of having the server enforce the relationship rather than the application.
Transactions that span several records
A write to one MongoDB document is atomic on its own, so a country and its embedded cities change together without a transaction. A write that spans several documents needs a multi-document transaction, and MongoDB runs those only on a replica set or a sharded cluster. On a standalone server the transaction fails at its first write:
const session = db.getMongo().startSession()
session.startTransaction()
session.getDatabase("geo").cities.insertOne({ _id: 106, name: "Nantes", population: 320000, country_id: 1 })
MongoServerError: Transaction numbers are only allowed on a replica set member or mongos
So if your MongoDB service uses transactions, your development setup needs a replica set, even one with a single member. InnoDB has no such condition: START TRANSACTION, COMMIT and ROLLBACK work on a single server, as part of its ACID model.
What a MongoDB validator enforces
MongoDB enforces a shape once you give a collection a $jsonSchema validator. This validator makes three fields of cities required:
db.runCommand({
collMod: "cities",
validator: { $jsonSchema: { required: ["name", "population", "country_id"] } }
})
db.cities.insertOne({ _id: 105, name: "Lille", popluation: 230000, country_id: 1 })
The validation action defaults to error, so MongoDB refuses the insert:
MongoServerError: Document failed validation
The error's errInfo lists population under missingProperties, which is how you find the misspelling in a larger document.
The validator checks inserts and updates, and leaves the stored documents as they are. Nice keeps its popluation field, and findOne({ _id: 104 }) still returns it. An update to Nice that leaves the misspelling in place now fails with "Document failed validation", so the first change to an old document has to fix it. The validator also sees only the document in front of it: a new city with country_id: 99 passes, because a validator can't look into another collection.
Finding the fields a MongoDB collection holds
In MySQL, SHOW CREATE TABLE lists a table's columns. A MongoDB collection without a validator has no definition to list: its shape is whatever its documents hold, including the popluation field in one of them.
DbSchema reads the documents of each collection, 100 from the start and 100 from the end unless you set a deeper scan, and lists every field it finds with its type. DbSchema shows a nested document as an object with its own fields, an array of documents as array[object], and a misspelled field in one of the documents it read as a field of its own. That field list is drawn from the documents, so MongoDB doesn't enforce it. For a collection that has a validator, DbSchema takes the fields from the validator instead.
The lines between collections are virtual relations. DbSchema draws one where a field holds the _id of a document in another collection, such as orders.customer_id, and keeps it in its model file; MongoDB never sees it.
If you settle on either database, or already run both, download DbSchema, connect to your MySQL or MongoDB database and reverse-engineer it into a diagram. Connecting, reverse-engineering and the interactive diagrams are in the free Community Edition.
Sources
- MySQL 9.7 Reference Manual
- MySQL 9.7 Reference Manual: Online DDL Operations
- MySQL 9.7 Reference Manual: FOREIGN KEY Constraints
- MySQL 9.7 Reference Manual: InnoDB and the ACID Model
- MongoDB Manual
- MongoDB Manual: Sharding
- MongoDB Manual: Embedding vs. References
- MongoDB Manual: Limits and Thresholds
- MongoDB Manual: $lookup
- MongoDB Manual: Model One-to-One Relationships with Embedded Documents
- MongoDB Manual: Transactions
- MongoDB Manual: Schema Validation
- MongoDB Manual: Handle Invalid Documents
Model MySQL and MongoDB side by side
DbSchema connects to both, reverse-engineers what is there, infers collection structure from sampled MongoDB documents, and draws the virtual relations the server never declares. Community covers connecting, reverse-engineering and the interactive diagrams.