Python Tutorial chapters (19)
  1. 01Python Introduction
  2. 02Python Syntax, Keywords & Operators
  3. 03Python Variables & Data Types
  4. 04Python Strings
  5. 05Python Control Statements
  6. 06Python Lists
  7. 07Python Tuples
  8. 08Python Sets
  9. 09Python Dictionaries
  10. 10Python Functions
  11. 11Python Modules
  12. 12Python OOPs
  13. 13Python Exception Handling
  14. 14Python File Handling
  15. 15Python Searching & Sorting
  16. 16Python Advanced Topics
  17. 17Python MySQL
  18. 18Python MongoDB & SQLite
  19. 19Python MCQ

Chapter 18

Python MongoDB & SQLite

2 topics · 2 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

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.

1

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.

App ↔ Database operations

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()
2

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

Code
import 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 failed

Solved examples

Example 01 · Basic

Write a pymongo query to find all students with marks above 60 and return only their names.

Given Data:
    Required To Find:

    Query

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: Filter {"marks": {"$gt": 60}}
    Step 2: Projection {"name": 1, "_id": 0}
    Final Answer: for doc in students.find({"marks": {"$gt": 60}}, {"name": 1, "_id": 0}): print(doc["name"])

    Approach note: Operators start with $ and are nested inside the field condition.

    Example 02 · Intermediate

    Insert a row into SQLite table users(name) for a name supplied by the user, safely.

    Given Data:
      Required To Find:

      Code

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: Use a ? placeholder
      Step 2: Pass a one-item tuple
      Step 3: Commit the transaction
      Final Answer: import sqlite3 conn = sqlite3.connect("app.db") conn.execute("CREATE TABLE IF NOT EXISTS users (name TEXT)") name = input("Name: ") conn.execute("INSERT INTO users (name) VALUES (?)", (name,)) conn.commit() conn.close()

      Approach note: Never build SQL text with f-strings from user input.

      Example 03 · Intermediate

      When should you choose SQLite over MongoDB?

      Given Data:
        Required To Find:

        Comparison

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: SQLite: relational, zero setup, single file, strong schema
        Step 2: MongoDB: flexible documents, horizontal scaling, needs a server
        Step 3: Pick SQLite for small local apps with tabular data
        Final Answer: Choose SQLite for embedded or small apps with structured, relational data and no server; choose MongoDB for flexible, evolving, document-shaped data at larger scale.

        Approach note: Mention schema flexibility vs relational integrity.

        Example 04 · Basic

        In SQLite, create table marks(id INTEGER PRIMARY KEY, score INTEGER), insert scores 70 and 85, then print the average score with SQL.

        Given Data:
          Required To Find:

          SQL + Python sketch

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: CREATE TABLE marks
          Step 2: INSERT two rows
          Step 3: SELECT AVG(score) → 77.5
          Final Answer: cur.execute("CREATE TABLE marks(id INTEGER PRIMARY KEY, score INTEGER)") cur.executemany("INSERT INTO marks(score) VALUES (?)", [(70,), (85,)]) print(cur.execute("SELECT AVG(score) FROM marks").fetchone()[0]) # 77.5

          Approach note: Use ? placeholders; never format user input into SQL strings.

          Real-world applications

          Python

          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.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          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

          1. MongoDB: client -> database -> collection -> documents (dicts).
          2. find / find_one with $gt, $in, $or; update with $set, $inc, $push.
          3. create_index(unique=True) prevents duplicates; aggregate for analytics.
          4. sqlite3 is built in; ? placeholders; commit() to save.
          5. with conn commits/rolls back but does not close.
          6. PRAGMA foreign_keys = ON to enforce foreign keys.

          Practice questions

          Question 1 · MCQ (Interview / semester)

          Which pymongo method inserts one document?

          Question 2 · MCQ (Interview / semester)

          Which update operator changes a field value?

          Question 3 · MCQ (Interview / semester)

          The sqlite3 placeholder for parameters is

          Question 4 · MCQ (Interview / semester)

          Which string creates an in-memory SQLite database?

          Question 5 · MCQ (Interview / semester)

          MongoDB stores data as

          Question 6 · MCQ (Interview / semester)

          To enforce foreign keys in SQLite you must run