🗄️ SQL for beginners · Class 12 · Lesson 4 of 18 · Free
MongoDB and NoSQL – Documents vs Tables, with JSON in SQL
⏱ About 35 minutes · ▶ run real SQL here — nothing to install · no sign-in
In this lesson you will
- Explain documents, collections and fields, and how they map to rows, tables and columns
- Read MongoDB insertOne() and find() queries
- Query JSON documents in SQL with json_extract, ->> and json_each
A school app saves each student's profile: name, city, a list of subjects, maybe a guardian, maybe not. Some students have 3 subjects, some 6, some none yet. Squeezing that into fixed columns feels awkward. MongoDB stores each profile as one flexible document instead, and SQL databases have learned the same trick with JSON.
What is MongoDB and how is a document different from a table row?
MongoDB is a popular NoSQL database. NoSQL means "not only SQL": databases that do not store data as tables of rows and columns.
MongoDB stores documents. A document looks like a JSON object: keys with values, and values can be lists (arrays) or other objects inside. A group of documents is a collection. So collection ≈ table, document ≈ row, field ≈ column.
There is no fixed list of columns. In the box below, Riya has subjects and a guardian, while Dev has neither. MongoDB also adds an _id field to every document by itself.
This is MongoDB shell code. It does not run on this page, which runs SQLite. Read it, then see the runnable SQL version in the next sections.
// One document: a student, with a list and a nested object inside
db.students.insertOne({
name: "Riya Sharma",
class: 12,
city: "Pune",
subjects: ["Maths", "Physics", "Computer Science"],
guardian: { name: "Sunita Sharma", relation: "Mother" }
})
// Many at once; documents need not have the same fields
db.students.insertMany([
{ name: "Aman Verma", class: 12, city: "Mumbai", subjects: ["Maths", "English"] },
{ name: "Dev Patil", class: 11, city: "Nagpur" }
])How does find() work in MongoDB compared with SQL SELECT?
find() is MongoDB's SELECT. You pass a filter document: { city: "Pune" } means WHERE city = 'Pune'. Two keys in one filter work like AND.
Operators start with $: $in is IN, $gte is >=. { subjects: "Maths" } finds documents whose subjects array contains "Maths". SQL needs more work for that, as you will see below.
The second argument picks fields, like the column list after SELECT. sort() and limit() work like ORDER BY and LIMIT from Lesson 1. updateOne() with $set changes one field, like UPDATE … SET.
Again, this is shown, not run. Compare each line with the SQL you already know.
db.students.find({ city: "Pune" }) // WHERE city = 'Pune'
db.students.find({ class: 12, city: "Pune" }) // … AND …
db.students.find({ city: { $in: ["Pune", "Mumbai"] } }) // city IN (…)
db.students.find({ subjects: "Maths" }) // array contains "Maths"
// SELECT name FROM students WHERE class = 12 ORDER BY name LIMIT 2
db.students.find({ class: 12 }, { name: 1, _id: 0 }).sort({ name: 1 }).limit(2)
// UPDATE students SET city = 'Pune' WHERE name = 'Dev Patil'
db.students.updateOne({ name: "Dev Patil" }, { $set: { city: "Pune" } })How do you store and read JSON documents in SQL?
Now the runnable part. SQLite, PostgreSQL and MySQL can all keep JSON text in a column. Here, the table student_docs has one doc column holding the same documents.
json_extract(doc, '$.name') reads a field. The path starts with $ (the whole document); a dot goes one level deeper, like '$.guardian.name'. A missing field gives NULL, just like a NULL column.
doc ->> '$.city' is a shorter way to write the same thing. SQLite 3.38+ and PostgreSQL both have ->>, though PostgreSQL writes the path as doc ->> 'city'.
Try it: change class 12 to 11, or read '$.guardian.relation'.
📋 Tables in this example: student_docs — tap to see how they are made
CREATE TABLE student_docs (
id INTEGER PRIMARY KEY,
doc TEXT NOT NULL
);
INSERT INTO student_docs (doc) VALUES
('{"name": "Riya Sharma", "class": 12, "city": "Pune", "subjects": ["Maths", "Physics", "Computer Science"], "guardian": {"name": "Sunita Sharma", "relation": "Mother"}}'),
('{"name": "Aman Verma", "class": 12, "city": "Mumbai", "subjects": ["Maths", "English"]}'),
('{"name": "Dev Patil", "class": 11, "city": "Nagpur"}'),
('{"name": "Meera Iyer", "class": 11, "city": "Chennai", "subjects": ["Computer Science", "English"], "guardian": {"name": "Lakshmi Iyer", "relation": "Mother"}}');┌────┬─────────────┬────────┐ │ id │ name │ city │ ├────┼─────────────┼────────┤ │ 1 │ Riya Sharma │ Pune │ │ 2 │ Aman Verma │ Mumbai │ └────┴─────────────┴────────┘ (2 rows) ┌─────────────┬───────────────┐ │ name │ guardian │ ├─────────────┼───────────────┤ │ Riya Sharma │ Sunita Sharma │ │ Aman Verma │ NULL │ │ Dev Patil │ NULL │ │ Meera Iyer │ Lakshmi Iyer │ └─────────────┴───────────────┘ (4 rows)
How do you search inside a JSON array in SQL?
MongoDB finds "subjects contains Computer Science" with one small filter. In SQL, json_each() turns an array into rows: one row per item, with the item in a column called value.
Below, every student row is paired with each of its subjects, and WHERE keeps the Computer Science ones. Dev has no subjects array, so he simply gives no rows.
json_set() changes one field inside the document, like MongoDB's $set. Try it: move Dev to 'Pune', or search for 'English' instead.
📋 Tables in this example: student_docs — tap to see how they are made
CREATE TABLE student_docs (
id INTEGER PRIMARY KEY,
doc TEXT NOT NULL
);
INSERT INTO student_docs (doc) VALUES
('{"name": "Riya Sharma", "class": 12, "city": "Pune", "subjects": ["Maths", "Physics", "Computer Science"], "guardian": {"name": "Sunita Sharma", "relation": "Mother"}}'),
('{"name": "Aman Verma", "class": 12, "city": "Mumbai", "subjects": ["Maths", "English"]}'),
('{"name": "Dev Patil", "class": 11, "city": "Nagpur"}'),
('{"name": "Meera Iyer", "class": 11, "city": "Chennai", "subjects": ["Computer Science", "English"], "guardian": {"name": "Lakshmi Iyer", "relation": "Mother"}}');┌─────────────┬──────────────────┐
│ name │ subject │
├─────────────┼──────────────────┤
│ Meera Iyer │ Computer Science │
│ Riya Sharma │ Computer Science │
└─────────────┴──────────────────┘
(2 rows)
1 row updated.
┌─────────────────────────────────────────────────┐
│ doc │
├─────────────────────────────────────────────────┤
│ {"name":"Dev Patil","class":11,"city":"Bhopal"} │
└─────────────────────────────────────────────────┘
(1 row)When should you use MongoDB instead of SQL?
Tables and documents can hold the same facts. This query builds one document per student from our school tables (marks joined to subjects). GROUP BY makes one row per student; you will learn it in Lesson 8.
Documents suit data that is read as one piece and whose shape changes often: a product with different details, an app's settings, a log of events.
Tables suit data with many links between parts: students, subjects, marks and fees. Keys and joins keep one copy of each fact, and the database checks the rules for you (Lesson 5). Most school, bank and shop systems use SQL for this reason.
Many apps use both, and SQL databases with JSON columns give you a bit of each. Try it: change (1, 6) to (4, 5).
📋 Tables in this example: students, subjects, teachers, marks, fees — tap to see how they are made
-- TalentJR practice school (made-up data for SQL lessons) CREATE TABLE students ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, class INTEGER NOT NULL, section TEXT NOT NULL, city TEXT, joined TEXT NOT NULL ); INSERT INTO students VALUES (1, 'Riya Sharma', 12, 'A', 'Pune', '2019-06-10'), (2, 'Aman Verma', 12, 'A', 'Mumbai', '2020-06-15'), (3, 'Sara Khan', 12, 'B', 'Pune', '2019-06-10'), (4, 'Dev Patil', 11, 'A', 'Nagpur', '2021-06-14'), (5, 'Meera Iyer', 11, 'B', 'Chennai', '2021-06-14'), (6, 'Kabir Singh', 12, 'B', 'Delhi', '2022-07-01'), (7, 'Anaya Joshi', 11, 'A', 'Pune', '2023-06-12'), (8, 'Rohan Das', 12, 'A', NULL, '2023-06-12'); CREATE TABLE subjects ( id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE ); INSERT INTO subjects VALUES (1, 'Maths'), (2, 'Physics'), (3, 'Chemistry'), (4, 'Computer Science'), (5, 'English'); CREATE TABLE teachers ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, subject_id INTEGER REFERENCES subjects(id) ); INSERT INTO teachers VALUES (1, 'Mrs. Kulkarni', 1), (2, 'Mr. Rao', 2), (3, 'Ms. Fernandes', 4), (4, 'Mr. Gupta', 5), (5, 'Mrs. Nair', NULL); CREATE TABLE marks ( student_id INTEGER NOT NULL REFERENCES students(id), subject_id INTEGER NOT NULL REFERENCES subjects(id), marks INTEGER NOT NULL CHECK (marks BETWEEN 0 AND 100), PRIMARY KEY (student_id, subject_id) ); INSERT INTO marks VALUES (1,1,92),(1,2,88),(1,3,79),(1,4,95),(1,5,84), (2,1,75),(2,2,68),(2,3,72),(2,4,81),(2,5,90), (3,1,81),(3,2,77),(3,3,85),(3,4,70),(3,5,88), (4,1,64),(4,2,58),(4,4,88),(4,5,71), (5,1,95),(5,2,91),(5,3,89),(5,4,93),(5,5,86), (6,1,55),(6,2,62),(6,3,49),(6,5,67), (7,1,73),(7,4,99),(7,5,80); CREATE TABLE fees ( student_id INTEGER NOT NULL REFERENCES students(id), month TEXT NOT NULL, amount INTEGER NOT NULL, paid INTEGER NOT NULL DEFAULT 0 ); INSERT INTO fees VALUES (1,'2026-06',4500,1),(1,'2026-07',4500,1),(2,'2026-06',4500,1),(2,'2026-07',4500,0), (3,'2026-06',4500,1),(4,'2026-06',4000,1),(4,'2026-07',4000,0),(5,'2026-06',4000,1), (6,'2026-06',4500,0),(7,'2026-06',4000,1),(8,'2026-06',4500,1);
┌────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ doc │
├────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ {"name":"Riya Sharma","marks":{"Maths":92,"Physics":88,"Chemistry":79,"Computer Science":95,"English":84}} │
│ {"name":"Kabir Singh","marks":{"Maths":55,"Physics":62,"Chemistry":49,"English":67}} │
└────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
(2 rows)🤔 Predict the output
Think like SQL: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this return?
SELECT json_extract('{"name": "Riya", "marks": {"maths": 92, "physics": 88}}', '$.marks.physics');Question 2. Document 3 is Dev Patil, who has no subjects field. What does this return?
📋 The tables (tap to see them)
CREATE TABLE student_docs (
id INTEGER PRIMARY KEY,
doc TEXT NOT NULL
);
INSERT INTO student_docs (doc) VALUES
('{"name": "Riya Sharma", "class": 12, "city": "Pune", "subjects": ["Maths", "Physics", "Computer Science"], "guardian": {"name": "Sunita Sharma", "relation": "Mother"}}'),
('{"name": "Aman Verma", "class": 12, "city": "Mumbai", "subjects": ["Maths", "English"]}'),
('{"name": "Dev Patil", "class": 11, "city": "Nagpur"}'),
('{"name": "Meera Iyer", "class": 11, "city": "Chennai", "subjects": ["Computer Science", "English"], "guardian": {"name": "Lakshmi Iyer", "relation": "Mother"}}');SELECT json_array_length(doc, '$.subjects') FROM student_docs WHERE id = 3;
Question 3. What does this return?
📋 The tables (tap to see them)
CREATE TABLE student_docs (
id INTEGER PRIMARY KEY,
doc TEXT NOT NULL
);
INSERT INTO student_docs (doc) VALUES
('{"name": "Riya Sharma", "class": 12, "city": "Pune", "subjects": ["Maths", "Physics", "Computer Science"], "guardian": {"name": "Sunita Sharma", "relation": "Mother"}}'),
('{"name": "Aman Verma", "class": 12, "city": "Mumbai", "subjects": ["Maths", "English"]}'),
('{"name": "Dev Patil", "class": 11, "city": "Nagpur"}'),
('{"name": "Meera Iyer", "class": 11, "city": "Chennai", "subjects": ["Computer Science", "English"], "guardian": {"name": "Lakshmi Iyer", "relation": "Mother"}}');SELECT j.value FROM student_docs AS d, json_each(d.doc, '$.subjects') AS j WHERE d.id = 1 ORDER BY j.value;
🧩 Your challenge
Using student_docs, list the name and city of every student who has 'English' in their subjects array. Sort by name. Expected: Aman Verma | Mumbai Meera Iyer | Chennai
┌────────────┬─────────┐ │ name │ city │ ├────────────┼─────────┤ │ Aman Verma │ Mumbai │ │ Meera Iyer │ Chennai │ └────────────┴─────────┘ (2 rows)
📋 Tables in this example: student_docs — tap to see how they are made
CREATE TABLE student_docs (
id INTEGER PRIMARY KEY,
doc TEXT NOT NULL
);
INSERT INTO student_docs (doc) VALUES
('{"name": "Riya Sharma", "class": 12, "city": "Pune", "subjects": ["Maths", "Physics", "Computer Science"], "guardian": {"name": "Sunita Sharma", "relation": "Mother"}}'),
('{"name": "Aman Verma", "class": 12, "city": "Mumbai", "subjects": ["Maths", "English"]}'),
('{"name": "Dev Patil", "class": 11, "city": "Nagpur"}'),
('{"name": "Meera Iyer", "class": 11, "city": "Chennai", "subjects": ["Computer Science", "English"], "guardian": {"name": "Lakshmi Iyer", "relation": "Mother"}}');⚠️ Common mistakes (and how to fix them)
❌ Wrong
SELECT json_extract(doc, 'name') FROM student_docs;
Error in statement 1 (SELECT): bad JSON path: 'name'
✅ Right
SELECT json_extract(doc, '$.name') FROM student_docs;
In SQLite a JSON path must start with $, which means "the whole document".
❌ Wrong
SELECT doc ->> '$.name' AS name FROM student_docs WHERE json_extract(doc, '$.class') = '12';
Runs, but gives the wrong result: (no rows) — columns: name
✅ Right
SELECT doc ->> '$.name' AS name FROM student_docs WHERE json_extract(doc, '$.class') = 12;
In the JSON, class is the number 12. json_extract gives back a number, and the number 12 is not equal to the text '12', so no rows match.
❌ Wrong
INSERT INTO student_docs (doc) VALUES ({"name": "Kabir Singh", "class": 12});Error: unrecognized token: "{"
✅ Right
INSERT INTO student_docs (doc) VALUES ('{"name": "Kabir Singh", "class": 12}');In SQL, a JSON document is just text, so it needs single quotes around it. Without them, SQL tries to read the braces as SQL.
📌 Remember
- MongoDB is a NoSQL database: collections of flexible documents instead of tables of rows.
- find({ … }) is MongoDB's SELECT … WHERE; $in, $gte and $set match IN, >= and UPDATE … SET.
- SQL databases can store JSON text too; json_extract(doc, '$.field') or doc ->> '$.field' reads a field.
- json_each() turns a JSON array into rows, so you can search inside lists.
- A missing JSON field gives NULL; JSON numbers are numbers, not text.
- Documents suit flexible, self-contained data; tables suit linked data with rules.
Finished the quiz and the challenge?
Questions students ask
Is MongoDB SQL or NoSQL?
MongoDB is NoSQL. It does not use SQL; you query it with methods like find() and filter documents written in JSON style. It stores documents, not tables.
Can a SQL database store JSON?
Yes. PostgreSQL has JSON and JSONB types, MySQL has a JSON type, and SQLite has JSON functions that work on text columns. You can mix normal columns and JSON in one table.
Is MongoDB better than SQL?
Neither is better everywhere. MongoDB is handy when each record has a different shape. SQL is better when data is linked and must follow strict rules, like marks that must belong to a real student.
Why does json_extract return NULL?
Usually the path does not exist in that document, or it is spelled differently (paths are case-sensitive). Check that the path starts with $ and matches the key names exactly.