MySQL Vs MongoDB
MySQL is a relational database that stores data in tables. MongoDB is a NoSQL document database that stores JSON-like documents. Both are popular, both are used with Java and Spring Boot, and both can power large applications. They suit different shapes of data and different styles of development.
1. Data Model: Tables vs Documents
| MySQL term | MongoDB term |
|---|---|
| Database | Database |
| Table | Collection |
| Row | Document |
| Column | Field |
| Primary key | _id field |
| JOIN | Embedding or $lookup |
| Index | Index |
2. Comparison Table
| Point | MySQL | MongoDB |
|---|---|---|
| Type | Relational (RDBMS) | Document-oriented NoSQL |
| Storage format | Rows in tables (InnoDB pages) | BSON documents (WiredTiger engine) |
| Schema | Fixed; changed with ALTER TABLE | Flexible; optional JSON-schema validation |
| Query language | SQL | MongoDB Query API (MQL) and aggregation pipelines |
| Relationships | Foreign keys and JOINs | Embedded documents, references, $lookup |
| Transactions | Full ACID, multi-row and multi-table | Single-document atomic; multi-document ACID since 4.0 |
| Scaling | Vertical, read replicas, InnoDB Cluster; sharding with extra tools | Built-in sharding and replica sets |
| Licence | GPL v2 / commercial | Server Side Public License (SSPL) / commercial |
| Default port | 3306 | 27017 |
3. Same Task, Two Syntaxes
Set up a small product table in MySQL:
CREATE DATABASE catalog;
USE catalog;
CREATE TABLE products (id INT PRIMARY KEY, name VARCHAR(40), brand VARCHAR(20), price INT, in_stock BOOLEAN);
INSERT INTO products VALUES
(1,'Running Shoes','Stride',3499,TRUE),(2,'Trail Shoes','Stride',4299,FALSE),
(3,'Yoga Mat','Flexi',899,TRUE),(4,'Dumbbell Set','IronMax',2599,TRUE);
Find in-stock products under 3,000, cheapest first. MySQL:
SELECT name, price FROM products
WHERE in_stock = TRUE AND price < 3000
ORDER BY price;
Result: 2 rows
| name | price |
|---|---|
| Yoga Mat | 899 |
| Dumbbell Set | 2599 |
MongoDB:
db.products.find(
{ in_stock: true, price: { $lt: 3000 } },
{ name: 1, price: 1, _id: 0 }
).sort({ price: 1 })
Average price per brand. MySQL:
SELECT brand, AVG(price) AS avg_price, COUNT(*) AS items
FROM products
GROUP BY brand
ORDER BY avg_price DESC;
Result: 3 rows
| brand | avg_price | items |
|---|---|---|
| Stride | 3899.0000 | 2 |
| IronMax | 2599.0000 | 1 |
| Flexi | 899.0000 | 1 |
MongoDB:
db.products.aggregate([
{ $group: { _id: "$brand", avg_price: { $avg: "$price" }, items: { $sum: 1 } } },
{ $sort: { avg_price: -1 } }
])
Update a price.
UPDATE products SET price = 3299 WHERE id = 1;
Query OK, 1 row affected
Rows matched: 1 Changed: 1 Warnings: 0
db.products.updateOne({ _id: 1 }, { $set: { price: 3299 } })
4. Schema: Strict vs Flexible
MySQL checks every row against the table definition. That stops mistakes early:
INSERT INTO products (id, name, brand, price, in_stock, colour) VALUES (5, 'Cap', 'Stride', 499, TRUE, 'red');
ERROR 1054 (42S22): Unknown column 'colour' in 'field list'
MongoDB accepts the extra colour field without any change, which is convenient for fast-changing data but means the application must keep the data tidy. In MySQL you would first run ALTER TABLE products ADD COLUMN colour VARCHAR(20);, or store optional attributes in a JSON column.
5. Relationships: Joins vs Embedding
- MySQL normalises data: each fact is stored once and joined when read. Updating a customer's address changes one row.
- MongoDB often embeds related data inside a document so one read returns everything. That is fast for reading, but duplicated data (for example, a product name copied into every order) must be updated in many places.
- MongoDB also supports references and the
$lookupstage, but deep, many-table joins are where SQL databases shine.
6. Transactions and Consistency
MySQL (InnoDB) has always supported multi-row, multi-table ACID transactions, and they are the normal way of working. In MongoDB a write to a single document is atomic, and multi-document transactions are available since version 4.0 (replica sets) and 4.2 (sharded clusters), but they have more overhead, and data models usually try to avoid needing them.
7. Performance and Scaling
- Both are fast when the data model and indexes match the queries. Neither is "always faster".
- MongoDB was designed for horizontal scaling: built-in sharding spreads a collection over many servers.
- MySQL usually scales reads with replicas and writes by scaling up; sharding needs application logic or tools such as Vitess.
- Reading a whole embedded document is a single lookup in MongoDB; the same data in MySQL may need a join, which is still fast with the right indexes.
8. Which Should You Choose?
| Choose MySQL when… | Choose MongoDB when… |
|---|---|
| Data is structured and relationships matter (orders, invoices, accounts) | Records vary a lot in shape (product catalogues, CMS content, event data) |
| You need strong multi-table transactions | You read and write whole objects at once |
| You need flexible reporting with SQL and joins | You need easy horizontal scaling across many servers |
| The team knows SQL well | Rapid prototyping with frequently changing fields |
9. Summary
- MySQL stores rows in tables with a fixed schema; MongoDB stores flexible BSON documents in collections.
- MySQL relates data with foreign keys and JOINs; MongoDB prefers embedding (plus
$lookup). - MySQL has mature multi-table ACID transactions; MongoDB has atomic single-document writes and newer multi-document transactions.
- MongoDB has built-in sharding; MySQL scales mainly with replicas and bigger servers.
- Choose by the shape of your data and how your application reads it.
Reference: Using MySQL as a Document Store – MySQL Reference Manual
https://dev.mysql.com/doc/refman/9.7/en/document-store.html