2384_1020_DOC_Python & MongoDB a Beginner's Guide
2384_1020_DOC_Python & MongoDB a Beginner's Guide
Handout
Project Overview: Building a Simple Python Application
that Interacts with MongoDB
Key Concepts:
MongoDB: A NoSQL database that stores data in a flexible, JSON-like format called
BSON.
CRUD Operations: Create, Read, Update, Delete operations on data.
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Access a database
db = client["mydatabase"]
# Access a collection
collection = db["mycollection"]
try:
collection.insert_one(document)
except pymongo.errors.PyMongoError as e:
print(f"An error occurred: {e}")
Error Logging
import logging
logging.basicConfig(filename='app.log', level=logging.ERROR)
try:
collection.insert_one(document)
except pymongo.errors.PyMongoError as e:
logging.error(f"An error occurred: {e}")
Performance Tips
Use Indexes: Speed up queries on large datasets.
Limit Results: Use limit() to fetch a specific number of documents.
Batch Processing: Process data in batches to manage memory usage.