Chapter 18
Python MongoDB & SQLite
2 topics · 2 sections · beginner-friendly study notes · Updated
MongoDB stores flexible JSON-like documents and is accessed with pymongo.
SQLite is a zero-configuration, file-based SQL database that ships inside Python as the sqlite3 module.
Together they cover document and relational storage without heavy infrastructure.
Choosing between document and relational storage and using each correctly is a core back-end skill.
MongoDB for catalogues, logs and content with changing shape; SQLite for desktop apps, mobile apps, prototypes, tests and small web sites.
Python MongoDB
MongoDB is a NoSQL document database that stores BSON (binary JSON) documents in collections inside databases. In Python the pymongo driver (pip install pymongo) connects with MongoClient; a database and collection are obtained by name and are created lazily on the first write.
In short: Instead of rows and columns you store dictionaries; each document can have a different shape.
Think about it
Document databases are widely used in modern web and data applications. Product catalogue where each product category has different attributes; storing user activity events.
Hierarchy: server -> database -> collection -> document (like a dict).
Every document has a unique _id (ObjectId by default).
CRUD: insert_one / insert_many, find_one / find, update_one / update_many / replace_one, delete_one / delete_many.
Query operators: $eq, $gt, $gte, $lt, $lte, $in, $nin, $and, $or, $not, $regex, $exists.
Update operators: $set, $unset, $inc, $push, $pull, $addToSet.
A projection ({"name": 1, "_id": 0}) limits returned fields; sort, skip and limit paginate.
create_index speeds up queries and enforces uniqueness.
The aggregation pipeline ($match, $group, $sort, $project, $lookup) performs analytics inside the server.
Handle pymongo.
errors.
DuplicateKeyError and ServerSelectionTimeoutError.
Use MongoDB when data is hierarchical or evolves quickly; prefer a relational database when you need many joins and strict transactions across tables.
Embedding related data in one document avoids joins.
Key points
- Document: JSON-like record stored as a Python dict.
- Collection: Group of documents, similar to a table.
- ObjectId: Default unique 12-byte identifier stored in _id.
- Aggregation pipeline: Series of stages that transform documents.
- Projection: Selection of which fields to
return.
Example
Code# pip install pymongo (and run a MongoDB server on localhost:27017)
from pymongo import MongoClient
from pymongo.errors import DuplicateKeyError, ServerSelectionTimeoutError
from bson import ObjectId
client = MongoClient("mongodb://localhost:27017", serverSelectionTimeoutMS=3000)
try:
client.admin.command("ping")
except ServerSelectionTimeoutError:
raise SystemExit("MongoDB server not reachable")
db = client["school"]
students = db["students"] # created on first insert
students.delete_many({}) # clean start for the demo
# Create
res = students.insert_one({"name": "Ana", "marks": 72, "skills": ["python", "sql"]})
print("inserted id:", res.inserted_id)
students.insert_many([
{"name": "Raj", "marks": 35, "skills": ["java"]},
{"name": "Lin", "marks": 90, "skills": ["python", "ml"]},
])
# Read
print(students.find_one({"name": "Ana"}))
for doc in students.find({"marks": {"$gte": 50}}, {"_id": 0, "name": 1, "marks": 1}).sort("marks", -1):
print(doc) # {'name': 'Lin', 'marks': 90} ...
print(students.count_documents({"skills": "python"})) # 2
print(students.find_one({"_id": ObjectId(str(res.inserted_id))})["name"]) # Ana
# Update
students.update_one({"name": "Raj"}, {"$set": {"marks": 80}})
students.update_many({}, {"$inc": {"marks": 5}})
students.update_one({"name": "Ana"}, {"$push": {"skills": "mongodb"}})
students.update_one({"name": "Zoe"}, {"$set": {"marks": 60}}, upsert=True)
# Delete
print(students.delete_one({"name": "Zoe"}).deleted_count) # 1
# Index and uniqueness
students.create_index("name", unique=True)
try:
students.insert_one({"name": "Ana"})
except DuplicateKeyError:
print("duplicate name rejected")
# Aggregation
pipeline = [
{"$match": {"marks": {"$gte": 40}}},
{"$group": {"_id": None, "avg_marks": {"$avg": "$marks"}, "n": {"$sum": 1}}},
]
print(list(students.aggregate(pipeline)))
client.close()Python SQLite
SQLite is a serverless, self-contained SQL database stored in a single file (or in memory with ":memory:"). Python includes it in the standard library as the sqlite3 module, so no installation or server is needed. Use sqlite3.connect(path), a cursor, execute with ? placeholders, and commit().
In short: A full SQL database that lives in one file and needs no server: perfect for small apps and learning.
Think about it
sqlite3 is the quickest way to practise real SQL from Python and is embedded in countless applications. Browsers, phones and desktop apps use SQLite files; developers use it for tests and prototypes.
Placeholders are ?
(or :name for named parameters); never concatenate user values into SQL.
conn.
row_factory = sqlite3.
Row allows access by column name.
Use executemany for bulk inserts and cursor.
lastrowid for the new id.
The connection used as a context manager (with conn:) commits on success and rolls back on exception but does NOT close the connection; call conn.
close() or use contextlib.
closing.
SQLite uses dynamic typing (type affinity): INTEGER, REAL, TEXT, BLOB, NUMERIC.
Foreign keys are off by default: run PRAGMA foreign_keys = ON per connection.
It supports joins, indexes, views, triggers and transactions, but allows only one writer at a time, so it is not ideal for high-concurrency servers.
Backup with conn.
backup().
Use ":memory:" for fast unit tests.
Prefer MySQL/PostgreSQL for large multi-user systems.
Key points
- Serverless: Runs inside your process; no separate server.
- :memory:: Temporary database that disappears on close.
- sqlite3.Row: Row object supporting access by name or index.
- Type affinity: SQLite flexible typing system.
- PRAGMA: SQLite command to configure behaviour.
Example
Codeimport sqlite3
from contextlib import closing
with closing(sqlite3.connect(":memory:")) as conn: # use "school.db" for a file
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
cur = conn.cursor()
cur.execute("""
CREATE TABLE students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
marks REAL DEFAULT 0
)
""")
cur.execute("""
CREATE TABLE courses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
student_id INTEGER NOT NULL REFERENCES students(id),
title TEXT NOT NULL
)
""")
cur.execute("INSERT INTO students (name, marks) VALUES (?, ?)", ("Ana", 72.5))
ana_id = cur.lastrowid
cur.executemany("INSERT INTO students (name, marks) VALUES (?, ?)", [("Raj", 35), ("Lin", 90)])
cur.executemany("INSERT INTO courses (student_id, title) VALUES (?, ?)",
[(ana_id, "Python"), (ana_id, "SQL")])
conn.commit()
for row in cur.execute("SELECT id, name, marks FROM students ORDER BY marks DESC"):
print(row["name"], row["marks"]) # Lin 90.0 / Ana 72.5 / Raj 35.0
cur.execute("UPDATE students SET marks = marks + ? WHERE name = ?", (5, "Raj"))
print("updated:", cur.rowcount) # 1
cur.execute("DELETE FROM students WHERE name = ?", ("Lin",))
conn.commit()
row = cur.execute("SELECT COUNT(*) AS n, AVG(marks) AS avg FROM students").fetchone()
print(row["n"], row["avg"]) # 2 56.25
joined = cur.execute("""
SELECT s.name, COUNT(c.id) AS courses
FROM students s LEFT JOIN courses c ON c.student_id = s.id
GROUP BY s.id ORDER BY s.name
""").fetchall()
print([dict(r) for r in joined]) # [{'name': 'Ana', 'courses': 2}, {'name': 'Raj', 'courses': 0}]
try:
with conn: # commit on success, rollback on error
conn.execute("INSERT INTO students (name) VALUES (?)", ("Temp",))
raise RuntimeError("something failed")
except RuntimeError:
pass
print(conn.execute("SELECT COUNT(*) FROM students").fetchone()[0]) # 2 (Temp rolled back)
try:
conn.execute("INSERT INTO courses (student_id, title) VALUES (?, ?)", (999, "Ghost"))
except sqlite3.IntegrityError as e:
print("IntegrityError:", e) # FOREIGN KEY constraint failedSolved examples
Write a pymongo query to find all students with marks above 60 and return only their names.
Query
Formula Applied:—Approach note: Operators start with $ and are nested inside the field condition.
Insert a row into SQLite table users(name) for a name supplied by the user, safely.
Code
Formula Applied:—Approach note: Never build SQL text with f-strings from user input.
When should you choose SQLite over MongoDB?
Comparison
Formula Applied:—Approach note: Mention schema flexibility vs relational integrity.
In SQLite, create table marks(id INTEGER PRIMARY KEY, score INTEGER), insert scores 70 and 85, then print the average score with SQL.
SQL + Python sketch
Formula Applied:—Approach note: Use ? placeholders; never format user input into SQL strings.
Real-world applications
Using Python MongoDB and SQLite in real projects
MongoDB for catalogues, logs and content with changing shape; SQLite for desktop apps, mobile apps, prototypes, tests and small web sites.
Common mistakes
❌ Myth: SQLite is just for toys.
Why this is wrong: It is among the most deployed databases in the world.
✅ Verified Truth: It is excellent for embedded and moderate-traffic use.
⚠️ Exam Tip: Mention its single-writer limit.
❌ Myth: MongoDB has no schema so design does not matter.
Why this is wrong: Poorly structured documents still cause slow, inconsistent data.
✅ Verified Truth: Plan document shape, indexes and validation.
⚠️ Exam Tip: Use indexes for frequent queries.
❌ Myth: with conn: closes the SQLite connection.
Why this is wrong: It only commits or rolls back.
✅ Verified Truth: Call conn.close() separately.
⚠️ Exam Tip: Use contextlib.closing for both.
Revision notes
MongoDB stores flexible JSON-like documents and is accessed with pymongo. SQLite is a zero-configuration, file-based SQL database that ships inside Python as the sqlite3 module. Together they cover document and relational storage without heavy infrastructure.
High-Yield Quick Revision Points
- MongoDB: client -> database -> collection -> documents (dicts).
- find / find_one with $gt, $in, $or; update with $set, $inc, $push.
- create_index(unique=True) prevents duplicates; aggregate for analytics.
- sqlite3 is built in; ? placeholders; commit() to save.
- with conn commits/rolls back but does not close.
- PRAGMA foreign_keys = ON to enforce foreign keys.
Practice questions
Which pymongo method inserts one document?
Which update operator changes a field value?
The sqlite3 placeholder for parameters is
Which string creates an in-memory SQLite database?
MongoDB stores data as
To enforce foreign keys in SQLite you must run