Pym on Go Presentation
Pym on Go Presentation
Integration
Guide with Implementation Details
Introduction to MongoDB & PyMongo
MongoDB: PyMongo:
- NoSQL, document-based. - Official Python driver for MongoDB.
- Stores data in BSON (Binary JSON). - Allows interaction with MongoDB via Python.
- Uses collections of documents instead of rows and tables.
-Cluster → Database → Collection → Documents. Installation:
pip install pymongo
Key Benefits:
- High flexibility and scalability. Basic Import:
- No fixed schema. from pymongo import MongoClient
- Easy replication and sharding.
Connecting to MongoDB Atlas with URI
URI Format :
"your_mongodb_uri"= mongodb+srv://<user>:<password>@<cluster>.mongodb.net/<db>?retryWrites=true&w=majority
Example :
"your_mongodb_uri"= mongodb+srv://viratkohli:password@democluster.mongodb.net/demo?retryWrites=true&w=majority
Note : URI format may change over time. You can obtain the current URI or its format during the MongoDB Atlas setup process.
CRUD Operations in PyMongo
Create: Update:
• insert_one() and insert_many() are used to add single • update_one() modifies a single matching document;
or multiple documents to a collection. update_many() applies changes to multiple.
• Automatically assigns a unique _id to each inserted • Uses operators like $set to update and $inc to increment values.
document. Code :
Code : (refer example 1 for complete code) collection.update_one({"name": "Alice"}, {"$set": {"age": 31}})
collection.insert_one({"name": "Alice", "age": 30}) collection.update_many({}, {"$inc": {"age": 1}})
collection.insert_many([{"name": "Bob"}, {"name": "Charlie"}])
Delete:
Read: • delete_one() removes the first matching document;
• find_one() retrieves the first matching document; find() delete_many() removes all that match the condition.
fetches all matching documents. • Useful for data cleanup or removing outdated records.
• Supports powerful query operators like $gte for filtering. Code :
Code : collection.delete_one({"name": "Alice"})
doc = collection.find_one({"name": "Alice"}) collection.delete_many({"age": {"$lt": 20}})
docs = list(collection.find({"age": {"$gte": 25}}))
Advanced Query Operators in PyMongo
Operator Description Example
$gt / $lt Greater / Less than {"age": {"$gt": 30}} (refer Example 2)
Arrays:
Embedded Documents:
• Fields can store lists, allowing multiple values like course names in a
• Documents can contain nested sub-documents for structured data (e.g.,
single document.
address inside user).
• Useful for modeling one-to-one relationships directly within a document. Code :
Code : (refer Example 6 ) student = {"name": "Bob", "courses": ["math", "science"]}
user = {"name": "Alice", "address": {"city": "NY", "zip": "10001"}} collection.insert_one(student)
collection.insert_one(user) Query Arrays:
Query Embedded: • Match documents containing specific values, all values, or based on array
length using $all and $size.
Use dot notation (e.g., "address.city") to query fields inside embedded
documents. Code :
Code : collection.find({"courses": "math"})
result = collection.find_one({"address.city": "NY"}) collection.find({"courses": {"$all": ["math", "science"]}})
collection.find({"courses": {"$size": 3}})
Summary & Best Practices
Summary:
- CRUD, Aggregation, Indexing, Transactions, Embedded Docs
- Code examples and URI management
- ObjectId usage and error handling
Best Practices:
- Use indexes wisely
- Validate data before transactions
- Avoid heavy $lookup/$group unless needed
- Use ObjectId for _id operations
- Use bulk_write and pipelines for speed
Examples :
Example 2 :
Example 1 :
from pymongo import MongoClient
from pymongo import MongoClient
# MongoDB Atlas URI
# Connect to MongoDB
uri = uri =
"mongodb+srv://viralkohli:password@democluster.mongodb.net/demo "mongodb+srv://viratkohli:password@democluster.mongodb.net/demo?retryWri
?retryWrites=true&w=majority" tes=true&w=majority"
# Connect to MongoDB client = MongoClient(uri)
client = MongoClient(uri)
# Access the database and collection # Access database and collection
db = client["demo"]
db = client["demo"] # "demo" is the database name
collection = db["users"]
collection = db["users"] # "users" is the collection name
# Sample query: find users where age > 26
# Insert a single document query = {"age": {"$gt": 26}}
collection.insert_one({"name": "Alice", "age": 30}) results = collection.find(query)