Module 3: Python–MongoDB Integration – Complete Chapter
In this module, we integrate Python with MongoDB. Using the pymongo library, you will learn to connect Python applications to MongoDB, perform CRUD operations, handle nested documents, and use aggregation pipelines.
By the end, you’ll be able to build Python programs that interact with MongoDB efficiently and safely.
✅ Installing PyMongo
PyMongo is the official Python driver for MongoDB.
# Install using pip
pip install pymongo
pip install dnspython # required for MongoDB Atlas
- Use a virtual environment for project isolation.
- Check version after installation:
import pymongo
print(pymongo.__version__)
✅ Connecting Python to MongoDB
🔹 Local MongoDB
from pymongo import MongoClient
# Connect to local MongoDB
client = MongoClient("mongodb://localhost:27017/")
db = client["mydb"]
collection = db["users"]
🔹 MongoDB Atlas
# Replace , ,
client = MongoClient("mongodb+srv://:@/test?retryWrites=true&w=majority")
db = client["mydb"]
collection = db["users"]
Best Practices: Never hardcode credentials; use environment variables or config files.
✅ CRUD Operations in Python
🔹 Create
# Insert a single document
user = {"name": "Ali", "age": 25, "role": "student"}
result = collection.insert_one(user)
print("Inserted ID:", result.inserted_id)
# Insert multiple documents
users = [
{"name": "Sara", "age": 22},
{"name": "John", "age": 30}
]
result = collection.insert_many(users)
print("Inserted IDs:", result.inserted_ids)
🔹 Read
# Find one document
user = collection.find_one({"name": "Ali"})
print(user)
# Find all documents
for u in collection.find():
print(u)
# Query with operators
for u in collection.find({"age": {"$gt": 20}}):
print(u)
🔹 Update
# Update one document
collection.update_one({"name": "Ali"}, {"$set": {"age": 26}})
# Update multiple documents
collection.update_many({}, {"$set": {"status": "active"}})
🔹 Delete
# Delete one
collection.delete_one({"name": "John"})
# Delete many
collection.delete_many({"age": {"$lt": 25}})
✅ Handling ObjectId in Python
from bson import ObjectId
# Find by ObjectId
doc_id = "64fbb123456789abcdef1234"
user = collection.find_one({"_id": ObjectId(doc_id)})
print(user)
Note: Always use ObjectId when querying by document ID.
✅ Working with Nested Documents
user = {
"name": "Ali",
"contact": {"email": "ali@example.com", "phone": "1234567890"},
"roles": ["student", "member"]
}
collection.insert_one(user)
# Access nested fields
result = collection.find_one({"name": "Ali"})
print(result["contact"]["email"])
Best Practices
- Keep nested structures manageable; deep nesting can slow queries.
- Use embedded documents for related data that is read together.
✅ Aggregation Pipeline
# Count users by role
pipeline = [
{"$unwind": "$roles"},
{"$group": {"_id": "$roles", "count": {"$sum": 1}}}
]
result = collection.aggregate(pipeline)
for doc in result:
print(doc)
Notes: Aggregation pipelines allow complex queries like group, filter, project, and sort.
✅ Error Handling in DB Operations
from pymongo.errors import ConnectionFailure, PyMongoError
try:
client.admin.command('ping')
print("Connected to MongoDB")
except ConnectionFailure:
print("Server not available")
except PyMongoError as e:
print("MongoDB error:", e)
Best Practices
- Always handle exceptions to prevent program crashes.
- Use timeouts and retries for production applications.
✅ Exercises
- Connect Python to a local MongoDB database and insert 5 user documents.
- Query all users older than 25 using Python.
- Update the status of a user and verify the change.
- Delete a document using its
ObjectId. - Create an aggregation pipeline to count users by age group.
Congratulations! You have completed Module 3: Python–MongoDB Integration.
You can now use Python programs to interact with MongoDB, perform CRUD operations, handle nested documents, and run aggregation queries.
In the next module, you will learn to build REST APIs in pure Python without any frameworks.
