Introduction to NoSQL Databases with Python: MongoDB and Redis Operations
This tutorial introduces NoSQL concepts and provides step‑by‑step Python code examples for installing, connecting, inserting, querying, updating, and deleting data in both MongoDB and Redis, highlighting their suitable use cases and key differences.
1. Introduction to NoSQL Databases
NoSQL (Not Only SQL) databases are non‑relational systems designed for large‑scale, high‑concurrency storage, offering key‑value, document, column, or graph models with high scalability and flexibility compared with traditional relational databases.
In Python, common NoSQL options include MongoDB (document store) and Redis (key‑value store). This article demonstrates how to operate both databases using Python, with complete code examples.
2. MongoDB Operations
2.1 Install PyMongo
Install the MongoDB driver for Python:
pip install pymongo2.2 Connect to MongoDB
from pymongo import MongoClient
# Connect to local MongoDB (default port 27017)
client = MongoClient("mongodb://localhost:27017/")
# Select database (created if not exists)
db = client["mydatabase"]
# Select collection (similar to a SQL table)
collection = db["users"]2.3 Insert Data
# Insert a single document
user = {"name": "Alice", "age": 25, "email": "[email protected]"}
insert_result = collection.insert_one(user)
print("Inserted document ID:", insert_result.inserted_id)
# Insert multiple documents
users = [
{"name": "Bob", "age": 30, "email": "[email protected]"},
{"name": "Charlie", "age": 35, "email": "[email protected]"}
]
insert_many_result = collection.insert_many(users)
print("Inserted document IDs:", insert_many_result.inserted_ids)2.4 Query Data
# Retrieve all documents
for doc in collection.find():
print(doc)
# Conditional query (age > 25)
query = {"age": {"$gt": 25}}
results = collection.find(query)
for user in results:
print(user)2.5 Update Data
# Update a single document
update_query = {"name": "Alice"}
new_values = {"$set": {"age": 26}}
collection.update_one(update_query, new_values)
# Update multiple documents
update_query = {"age": {"$gt": 25}}
new_values = {"$set": {"status": "active"}}
collection.update_many(update_query, new_values)2.6 Delete Data
# Delete a single document
delete_query = {"name": "Alice"}
collection.delete_one(delete_query)
# Delete multiple documents
delete_query = {"age": {"$gt": 30}}
collection.delete_many(delete_query)3. Redis Operations
3.1 Install redis‑py
pip install redis3.2 Connect to Redis
import redis
# Connect to local Redis (default port 6379)
r = redis.Redis(host="localhost", port=6379, db=0)
print("Ping:", r.ping()) # True indicates successful connection3.3 Basic Key‑Value Operations
# Set a key
r.set("username", "alice")
# Get the key
username = r.get("username")
print(username.decode("utf-8"))
# Set a key with expiration (10 seconds)
r.setex("temp_data", 10, "this will expire in 10 seconds")
# Check existence
print(r.exists("username"))3.4 Hash Operations (store objects)
# Store a hash
user_data = {"name": "Bob", "age": "30", "email": "[email protected]"}
r.hset("user:1001", mapping=user_data)
# Retrieve a field
name = r.hget("user:1001", "name")
print(name.decode("utf-8"))
# Retrieve the whole hash
user = r.hgetall("user:1001")
for key, value in user.items():
print(key.decode("utf-8"), ":", value.decode("utf-8"))3.5 List Operations (suitable for queues)
# Push items to the left of a list
r.lpush("tasks", "task1", "task2", "task3")
# Get list length
print(r.llen("tasks"))
# Pop from the right (FIFO)
task = r.rpop("tasks")
print(task.decode("utf-8"))4. Summary
MongoDB excels at storing complex, dynamic JSON‑like documents, while Redis provides high‑speed read/write, caching, and real‑time data handling. Mastering both NoSQL databases equips Python developers with flexible storage options for a wide range of applications.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.