Lecture 08 · Module 2

Saving Streams to MongoDB

MongoDB Atlas Setup · Python Consumer · Persistent Storage

📅 Module 2 — Making Kafka Work
90 min
🎓 MBA Streaming Data Analytics
02 / 08 Agenda

Today's 90 Minutes

TimeSegmentFormat
0 – 10Recap — consumer_stock.py from Lecture 7Q&A
10 – 20Why save streaming data? Storage optionsLecture
20 – 40MongoDB Atlas — free cluster setupDemo
40 – 45Install pymongo + test connectionLab
45 – 75consumer_mongodb.py — save to AtlasLab
75 – 85Verify in Atlas dashboard + query dataDemo
85 – 90Takeaways + Lecture 9 previewWrap-up
03 / 08 Concept

Why Save Streaming Data?

A Kafka consumer that only prints to the terminal loses everything the moment you close it. Persistence unlocks the business value.

📊 Batch Analysis
Run SQL or Pandas queries later
End-of-day portfolio report, weekly trend charts
🔁 ML Training Data
Build models from historical stream
Price prediction, anomaly detection
📋 Audit Trail
Immutable record of every event
Regulatory compliance, fraud review
🔔 Replay & Recovery
Re-process if a consumer crashes
Restart without losing any messages
Storage OptionBest ForOur Choice
SQLite (file)Simple local demos
MongoDB AtlasJSON docs, free cloud, scale✅ Today
PostgreSQLRelational, strong SQL
S3 / Cloud StorageBig data lake, cheapest
04 / 08 Setup

MongoDB Atlas — Free Cluster Setup

Takes about 5 minutes. You get 512 MB free forever — more than enough for this course.

  1. Go to https://www.mongodb.com/cloud/atlas → click Try Free → sign up with Google or email.
  2. Choose M0 Free tier → pick AWS Mumbai (ap-south-1) → click Create Deployment.
  3. Create a database user — set a username and password. Write these down — you'll need them in your Python code.
  4. Network Access → Add IP Address → Allow Access from Anywhere (0.0.0.0/0). This lets your laptop connect.
  5. Click Connect → Drivers → Python → copy the connection string. It looks like:
    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.

05 / 08 Lab

Install pymongo & Test Connection

Install

bash
pip install pymongo kafka-python

Test your Atlas connection

python · test_mongo.py
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.

06 / 08 Lab

consumer_mongodb.py — Save Every Message

python · consumer_mongodb.py
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}")
07 / 08 Demo

Verify in Atlas Dashboard

After running consumer_mongodb.py, check your data in the Atlas web UI.

  1. In Atlas → click Browse Collections
  2. Navigate to sda_course → stock_prices
  3. You'll see all saved JSON documents with symbol, price, _saved_at

Query from Python

python
# 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.

08 / 08 Wrap-Up

Key Takeaways

Download Lab Files

Next → Lecture 9: Build a live analytics dashboard from MongoDB data using Streamlit

1 / 8