00:00

MySQL Vs MongoDB

Last updated:

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

One blog post with comments in MySQL and in MongoDBIn MySQL the post is one row in posts and its comments are rows in a separate comments table linked by post_id. In MongoDB the post is one document with an embedded array of comments.MySQL: two related tablespostspost_idtitle1Hello MySQLcommentsidpost_idauthortext11RaviNice!21MitaThanksJOIN on post_id to read a post with its commentsMongoDB: one document{  _id: 1,  title: "Hello MongoDB",  comments: [    { author: "Ravi", text: "Nice!" },    { author: "Mita", text: "Thanks" }  ]}One read returns the post and its comments
Figure 1: relational tables split data and join it back; documents keep related data together.
MySQL termMongoDB term
DatabaseDatabase
TableCollection
RowDocument
ColumnField
Primary key_id field
JOINEmbedding or $lookup
IndexIndex

2. Comparison Table

PointMySQLMongoDB
TypeRelational (RDBMS)Document-oriented NoSQL
Storage formatRows in tables (InnoDB pages)BSON documents (WiredTiger engine)
SchemaFixed; changed with ALTER TABLEFlexible; optional JSON-schema validation
Query languageSQLMongoDB Query API (MQL) and aggregation pipelines
RelationshipsForeign keys and JOINsEmbedded documents, references, $lookup
TransactionsFull ACID, multi-row and multi-tableSingle-document atomic; multi-document ACID since 4.0
ScalingVertical, read replicas, InnoDB Cluster; sharding with extra toolsBuilt-in sharding and replica sets
LicenceGPL v2 / commercialServer Side Public License (SSPL) / commercial
Default port330627017

3. Same Task, Two Syntaxes

Set up a small product table in MySQL:

setup.sql
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:

query.sql
SELECT name, price FROM products
WHERE in_stock = TRUE AND price < 3000
ORDER BY price;

Result: 2 rows

nameprice
Yoga Mat899
Dumbbell Set2599

MongoDB:

mongosh
db.products.find(
  { in_stock: true, price: { $lt: 3000 } },
  { name: 1, price: 1, _id: 0 }
).sort({ price: 1 })

Average price per brand. MySQL:

query.sql
SELECT brand, AVG(price) AS avg_price, COUNT(*) AS items
FROM products
GROUP BY brand
ORDER BY avg_price DESC;

Result: 3 rows

brandavg_priceitems
Stride3899.00002
IronMax2599.00001
Flexi899.00001

MongoDB:

mongosh
db.products.aggregate([
  { $group: { _id: "$brand", avg_price: { $avg: "$price" }, items: { $sum: 1 } } },
  { $sort: { avg_price: -1 } }
])

Update a price.

query.sql
UPDATE products SET price = 3299 WHERE id = 1;
Output
Query OK, 1 row affected
Rows matched: 1  Changed: 1  Warnings: 0
mongosh
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:

query.sql
INSERT INTO products (id, name, brand, price, in_stock, colour) VALUES (5, 'Cap', 'Stride', 499, TRUE, 'red');
Output
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 $lookup stage, 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 transactionsYou read and write whole objects at once
You need flexible reporting with SQL and joinsYou need easy horizontal scaling across many servers
The team knows SQL wellRapid prototyping with frequently changing fields
Many systems use both: MySQL for orders and payments, MongoDB for a flexible product catalogue or activity feed. See the MongoDB tutorial to learn it.

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