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