NoSQL with Python
NoSQL with Python
Section titled “NoSQL with Python”Introduction
Section titled “Introduction”NoSQL databases offer flexible schemas and horizontal scaling. Python integrates well with popular NoSQL databases like MongoDB and Redis.
MongoDB with PyMongo
Section titled “MongoDB with PyMongo”from pymongo import MongoClient
# Connectclient = MongoClient("mongodb://localhost:27017")db = client["mydatabase"]collection = db["users"]
# Createuser = { "name": "Alice", "email": "alice@example.com", "age": 30, "skills": ["Python", "MongoDB"], "address": {"city": "NYC", "zip": "10001"}}result = collection.insert_one(user)print(result.inserted_id)
# Readuser = collection.find_one({"email": "alice@example.com"})users = collection.find({"age": {"$gte": 25}})for user in users: print(user["name"])
# Updatecollection.update_one( {"email": "alice@example.com"}, {"$set": {"age": 31}, "$push": {"skills": "Docker"}})
# Deletecollection.delete_one({"email": "alice@example.com"})
# Aggregation pipelinepipeline = [ {"$match": {"age": {"$gte": 25}}}, {"$group": {"_id": "$city", "avg_age": {"$avg": "$age"}}}, {"$sort": {"avg_age": -1}}]results = collection.aggregate(pipeline)Redis with redis-py
Section titled “Redis with redis-py”import redis
# Connectr = redis.Redis(host="localhost", port=6379, db=0)
# Stringsr.set("key", "value")print(r.get("key")) # b'value'
# With expirationr.setex("temp", 60, "expires in 60s")
# Listsr.lpush("queue", "job1", "job2", "job3")print(r.lrange("queue", 0, -1)) # All items
# Setsr.sadd("tags", "python", "redis", "database")print(r.smembers("tags"))
# Hashesr.hset("user:1", mapping={"name": "Alice", "age": 30})print(r.hgetall("user:1"))Choosing SQL vs NoSQL
Section titled “Choosing SQL vs NoSQL”| Feature | SQL | NoSQL |
|---|---|---|
| Schema | Fixed, predefined | Flexible, dynamic |
| Relationships | Joins, foreign keys | Embedded documents, references |
| Scaling | Vertical (mostly) | Horizontal (built-in) |
| ACID | Full support | Varies (eventual consistency) |
| Query | Structured (SQL) | API-based, aggregation |
| Best for | Complex relationships | Large scale, flexible data |
Best Practices
Section titled “Best Practices”- Use indexes in MongoDB for frequently queried fields
- Use connection pooling for production database access
- Validate data before inserting into NoSQL databases
- Use appropriate data types — MongoDB BSON, Redis hashes
- Handle disconnections gracefully with retry logic
Practice Exercises
Section titled “Practice Exercises”Exercise 1: Design a product catalog using MongoDB with embedded categories and reviews.
Exercise 2: Implement a simple cache layer using Redis with TTL-based expiration.