← Back to MongoDB Course | Chapter 1: Introduction | Lesson 2 of 7

SQL vs NoSQL

SQL databases keep data in strict tables of rows and columns, while NoSQL databases like MongoDB use more flexible models.

In this page:

  1. SQL vs NoSQL

SQL vs NoSQL

Relational databases require a schema up front, use joins across normalized tables and speak SQL. MongoDB keeps related data together in one document, allows fields to vary, and uses a JSON query language.

Neither is better in general: choose by data shape, consistency needs and team skills.

Note: A SQL row is roughly a MongoDB document, and a table is roughly a collection.

Example: SQL vs NoSQL

bash
// SQL:   SELECT name FROM users WHERE age > 30 ORDER BY name;
// Mongo: the same question as a query document
test> db.users.insertMany([{ _id: 1, name: "Cy", age: 41 }, { _id: 2, name: "Ada", age: 36 }, { _id: 3, name: "Bob", age: 25 }])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2, '2': 3 } }
test> db.users.find({ age: { $gt: 30 } }, { name: 1, _id: 0 }).sort({ name: 1 })
[ { name: 'Ada' }, { name: 'Cy' } ]

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Assuming NoSQL means no transactions
  2. Assuming SQL cannot scale
  3. Copying a relational schema into MongoDB unchanged
Chapter Summary
  • SQL uses tables, rows and joins
  • MongoDB uses collections and documents
  • MongoDB documents can vary in shape
  • Choose by data and access patterns
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.