Skip to content

MongoDB Fundamentals

MongoDB vs SQL

Documents versus rows, flexible schema, relationships, and the practical trade-offs.

BeginnerAbout 6 minutes

Same data, two shapes. SQL stores Rahul as a row in a users table. MongoDB stores Rahul as a document in a users collection. Neither is universally better. The access pattern decides.

SQL

  • Database → table → row → column
  • JOIN at read time
  • Schema declared in DDL
  • Transactions as a comfortable default

MongoDB

  • Database → collection → document → field
  • Embed, or reference and $lookup
  • Schema in documents (validators optional)
  • Single-document atomicity first
SQLMongoDB
DatabaseDatabase
TableCollection
RowDocument
ColumnField
JOIN$lookup (later) or embed

A practical example

SELECT u.name, o.amount
FROM users u
JOIN orders o ON o.user_id = u.id
WHERE u.city = 'Bangalore';
SQL: users and orders in two tables
// Profile read: one document, skills already on it
db.users.findOne({ city: "Bangalore" })

// Orders stay in their own collection and point at the user
db.orders.find({ userId: ObjectId("64a1b2c3d4e5f6a7b8c90001") })
MongoDB: often you model so the common read needs no join

Skills sit inside the user document. That is embedding. Orders stay in orders and store userId. That is referencing. You embed what you always load with the parent. You reference what grows without bound — orders, events, comments. Data modeling later is the full version of that decision.

Schema, joins, transactions, scale

  • Schema. SQL rejects an unknown column. MongoDB will store a new field on one document and not on the next. Faster to evolve, easier to get inconsistent. Validation and a single owning service put the rails back.
  • Joins. SQL JOINs are the normal way to compose a read. MongoDB can $lookup, but if every request joins three collections, the schema is probably fighting you.
  • Transactions. MongoDB can run multi-document transactions. A single document update is already atomic. Reach for a transaction when two documents must change together — not as the default write path. That module comes later.
  • Scale. SQL often scales up, then replicas. MongoDB replicas are the normal production setup; sharding is a later, specialist step. Do not pick MongoDB 'because it scales' without an access pattern that benefits.

When to choose which

  • MongoDB — the common read is a document with nested data; the shape is still moving; you want to avoid a join on the hot path.
  • SQL — the common read is relational (orders × customers × payments); you want constraints and joins as the default; reporting is tabular.

Interview question

When would you choose MongoDB, and when would you choose SQL?

Think about it first.

Interview question

Is MongoDB schemaless?

Think about it first.

Practice

Read real documents from the same users collection these lessons use.