MongoDB Atlas Setup · Python Consumer · Persistent Storage
| Time | Segment | Format |
|---|---|---|
| 0 – 10 | Recap — consumer_stock.py from Lecture 7 | Q&A |
| 10 – 20 | Why save streaming data? Storage options | Lecture |
| 20 – 40 | MongoDB Atlas — free cluster setup | Demo |
| 40 – 45 | Install pymongo + test connection | Lab |
| 45 – 75 | consumer_mongodb.py — save to Atlas | Lab |
| 75 – 85 | Verify in Atlas dashboard + query data | Demo |
| 85 – 90 | Takeaways + Lecture 9 preview | Wrap-up |
A Kafka consumer that only prints to the terminal loses everything the moment you close it. Persistence unlocks the business value.
| Storage Option | Best For | Our Choice |
|---|---|---|
| SQLite (file) | Simple local demos | — |
| MongoDB Atlas | JSON docs, free cloud, scale | ✅ Today |
| PostgreSQL | Relational, strong SQL | — |
| S3 / Cloud Storage | Big data lake, cheapest | — |
Takes about 5 minutes. You get 512 MB free forever — more than enough for this course.
mongodb+srv://username:password@cluster0.xxxxx.mongodb.net/
✅ Test your connection — paste your URI into the connection test on the next slide before running the full consumer.
pip install pymongo kafka-python
from pymongo import MongoClient
MONGO_URI = "mongodb+srv://username:password@cluster0.xxxxx.mongodb.net/"
client = MongoClient(MONGO_URI)
# List databases to confirm connection works
dbs = client.list_database_names()
print("✅ Connected! Databases:", dbs)
# Write a test document
db = client["sda_course"]
db["test"].insert_one({"hello": "world"})
print("✅ Test document inserted!")
Common error: Authentication failed — double-check your username/password in the URI. Passwords with @ or # must be URL-encoded.
from kafka import KafkaConsumer
from pymongo import MongoClient
import json
from datetime import datetime
MONGO_URI = "mongodb+srv://username:password@cluster0.xxxxx.mongodb.net/"
client = MongoClient(MONGO_URI)
db = client["sda_course"]
collection = db["stock_prices"]
print(f"✅ Connected → {db.name}.{collection.name}")
consumer = KafkaConsumer(
'stock-topic',
bootstrap_servers=['localhost:9092'],
auto_offset_reset='earliest',
value_deserializer=lambda x: json.loads(x.decode('utf-8'))
)
saved = 0
print("📡 Listening on stock-topic...")
for msg in consumer:
data = msg.value
data['_saved_at'] = datetime.utcnow().isoformat()
result = collection.insert_one(data)
saved += 1
sym = data.get('symbol', '?')
price = data.get('price', data.get('Close', '?'))
print(f"💾 [{sym}] ₹{price} → saved #{saved}")
After running consumer_mongodb.py, check your data in the Atlas web UI.
symbol, price, _saved_at# Count documents per symbol
from pymongo import MongoClient
client = MongoClient(MONGO_URI)
col = client["sda_course"]["stock_prices"]
print("Total saved:", col.count_documents({}))
print("TCS records:", col.count_documents({"symbol": "TCS.NS"}))
print("INFY records:", col.count_documents({"symbol": "INFY.NS"}))
# Get latest 5 TCS prices
for doc in col.find({"symbol":"TCS.NS"}).sort("_id", -1).limit(5):
print(doc["symbol"], doc.get("price", doc.get("Close")))
This is your Assignment 3 foundation. The same pattern — consumer → MongoDB → query — powers your streaming analytics dashboard.
_saved_at, _kafka_offset make debugging much easiercount_documents, find, sort, limit are your core toolsNext → Lecture 9: Build a live analytics dashboard from MongoDB data using Streamlit