Lesson 2 +10 XP

SQL vs Document Databases

SQL vs Document Databases

SQL databases are relational. They store related data in separate tables and you use joins to pull data back together when you query it.

MongoDB is a document database, often called non-relational or NoSQL. That doesn't mean you can't store related data - it just stores it differently.

Tables become collections

SQL termMongoDB term
TableCollection
RowDocument
ColumnField
Primary key_id
Join$lookup (or embed data)

Related data stays together

With SQL you spread data across tables and join them later. With MongoDB you can keep related data in one document, which makes reading very fast:

{
  title: "Post Title 1",
  body: "Body of post.",
  category: "News",
  likes: 1,
  author: {
    name: "Ada",
    email: "ada@example.com"
  },
  comments: [
    { user: "Grace", text: "Nice post!" }
  ]
}

Flexible schema

A SQL table forces every row to have the same columns. A MongoDB collection does not force documents to share a structure. One document might have a tags field while another doesn't - that's fine.

When document databases shine

  • Rapid prototyping and iteration.
  • Data that looks like objects in your code.
  • Hierarchical or nested data.
  • When you need to scale horizontally.

TL;DR

  • SQL: tables + rows + joins; rigid schema.
  • MongoDB: collections + documents; flexible schema.
  • Related data can live together in one document.