69
MongoDB
Python & MongoDB: From In-Memory Data to Persistence
What you're probably confused about right now
"I can store data in a dict. Why do I need a database?"
A dict vanishes when the process ends. Databases give you long-term storage and querying.
One-line definition
MongoDB is a document database -- great for JSON-style data storage and rapid iteration.
Real-life analogy
A dict is a sticky note. MongoDB is a searchable filing cabinet.
Minimal working example
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
users = client["jr_demo"]["users"]
users.insert_one({"name": "Alice", "age": 25})
print(users.find_one({"name": "Alice"}))
Quick quiz (5 min)
- Insert 3 user documents.
- Query for age > 20.
- Update a record, then query again to confirm.
Quiz answer guide & grading criteria
- Answer direction: write runnable code that covers the core requirements and edge cases from the prompt.
- Criterion 1 (Correctness): Main flow produces correct results, key branches execute.
- Criterion 2 (Readability): Clear variable names, no excessive nesting.
- Criterion 3 (Robustness): Basic protection against null values, type errors, or unexpected input.
Take-home task
Implement a minimal CRUD service (create/find/update/delete).
Acceptance criteria
You can independently:
- Connect to MongoDB
- Perform basic CRUD operations
- Understand how indexes affect query performance
Common errors & debugging steps (beginner edition)
- Can't read the error: start from the last line -- find the error type (
TypeError,NameError, etc.), then trace back to the line in your code. - Not sure about a variable's value: throw in a temporary
print(var, type(var))at key points to verify data looks right. - Changed code but nothing happened: make sure the file is saved, you're running the right file, and your terminal is in the correct venv.
Common misconceptions
- Misconception: MongoDB doesn't need field schema design.
- Reality: the earlier you standardize, the lower the cost down the road.