Use PyMongo or Motor (async) in Python apps—connection pooling and BSON types matter in production.
PyMongo insert and find
# pip install pymongo
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017')
db = client['practice']
db.products.insert_one({'sku': 'Z9', 'price': 3.5})
list(db.products.find({'price': {'$lt': 10}}).limit(5))Practice: Review prior lessons in mongosh, then attempt interview-style queries without peeking.
Best practices
- Reuse one MongoClient per process (thread-safe pool)
- Use UTC datetimes; store money as Decimal128 or integer cents
- Index fields your find() and aggregation $match use
- Use transactions API for multi-doc flows when needed
Django note
Django prefers SQL ORM—MongoDB often pairs with FastAPI/Flask microservices or dedicated services, not classic Django ORM.
Important interview questions and answers
- Q: One MongoClient?
A: Expensive to connect per request—pool inside client. - Q: Motor?
A: Async wrapper for asyncio apps.
Self-check
- Why reuse MongoClient?
- How filter by price less than 10 in Python dict?
Pitfall: Creating MongoClient per request—reuse one client per process.
Interview prep
- MongoClient reuse?
- One client per process with connection pool.
- Motor?
- Async PyMongo for asyncio services.