iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PyMongo

MongoDB Python driver (PyMongo): connection, CRUD, aggregation, async with motor.

MongoDB — Python driver

EXAMPLE
# Install: pip install pymongo
from pymongo import MongoClient
from bson import ObjectId
import os

# ===== Connect =====
client = MongoClient(
    os.environ['MONGO_URI'],
    maxPoolSize=50,
    serverSelectionTimeoutMS=5000,
    retryWrites=True,
    appName='shop',
)
db = client.shop
users = db.users

# ===== Insert =====
result = users.insert_one({'email': 'a@x.io', 'name': 'Alex'})
print(result.inserted_id)

users.insert_many([{'email': 'b@x.io'}, {'email': 'c@x.io'}])

# ===== Find =====
u = users.find_one({'_id': ObjectId(id)})

cursor = users.find({'active': True}).sort('created_at', -1).limit(20)
for doc in cursor:
    print(doc)

# Just count:
n = users.count_documents({'active': True})

# Projection:
list = list(users.find({}, {'password': 0}).limit(20))

# ===== Update =====
users.update_one(
    {'_id': ObjectId(id)},
    {'$set': {'name': 'Sam'}, '$inc': {'logins': 1}},
    upsert=True,
)

users.update_many({'country': 'AU'}, {'$set': {'region': 'APAC'}})

# ===== Delete =====
users.delete_one({'_id': ObjectId(id)})
users.delete_many({'created_at': {'$lt': cutoff}})

# ===== Aggregation =====
pipeline = [
    {'$match': {'status': 'paid'}},
    {'$group': {'_id': '$customer_id', 'total': {'$sum': '$amount'}}},
    {'$sort': {'total': -1}},
    {'$limit': 10},
]
top = list(db.orders.aggregate(pipeline))

# ===== Indexes =====
users.create_index([('email', 1)], unique=True)
users.create_index([('country', 1), ('region', 1)])

# ===== Transactions =====
with client.start_session() as session:
    with session.start_transaction():
        accounts.update_one({'_id': from_id}, {'$inc': {'balance': -50}}, session=session)
        accounts.update_one({'_id': to_id}, {'$inc': {'balance': 50}}, session=session)

# ===== Async with motor =====
# pip install motor
from motor.motor_asyncio import AsyncIOMotorClient
import asyncio

async def main():
    client = AsyncIOMotorClient(os.environ['MONGO_URI'])
    db = client.shop
    u = await db.users.find_one({'email': 'a@x.io'})
    async for doc in db.users.find().limit(10):
        print(doc)

asyncio.run(main())

# ===== ODM: Beanie (motor-based) =====
# pip install beanie
from beanie import Document, init_beanie

class User(Document):
    email: str
    name: str

async def setup():
    await init_beanie(database=db, document_models=[User])
    user = User(email='a@x.io', name='Alex')
    await user.insert()
    found = await User.find_one(User.email == 'a@x.io')

# ===== Patterns =====
# - One client per process; close on shutdown
# - Use motor for async apps
# - ODM (Beanie) when schemas help; pymongo when raw control needed
# - Cursor iteration for large result sets

# ===== Pitfalls =====
# - Connecting per request
# - Forgetting list(cursor) when you need a materialised list
# - Mixing sync + async clients in the same code
# - Missing indexes on hot query paths

Why it matters

PyMongo for sync apps, Motor for async, Beanie when you want a Pydantic-style ODM. Same shape as the Node driver: one client per process, indexes for queries, transactions when atomicity matters.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client.shop
for u in db.users.find(): print(u)
Try it Yourself »

Discussion

Loading…