Pythonpymongov4.10.1
PythonIntermediate

pymongo

Official MongoDB driver for Python — insert, query, update, and aggregate documents with a Pythonic API.

databasemongodbnosqlasync
The Problem

You're using MongoDB and need to interact with it from Python. Whether it's inserting documents, running complex aggregation pipelines, or managing indexes, you need a driver that maps naturally to Python dicts.

Mental Model

MongoDB documents are JSON objects. pymongo maps them to Python dicts. A MongoClient connects to the cluster, you select a database and collection like attribute access (client.mydb.users), then call methods like .insert_one(), .find(), .update_many(). Aggregation pipelines are just lists of stage dicts.

60-second start

Basic CRUD operations

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
db = client.myapp
users = db.users

# Insert
result = users.insert_one({'name': 'Alice', 'email': 'alice@example.com', 'age': 30})
print(result.inserted_id)
# Find one
user = users.find_one({'email': 'alice@example.com'})
print(user['name'])

# Find many
for u in users.find({'age': {'$gte': 18}}).sort('name').limit(10):
    print(u['name'])

# Update
users.update_one(
    {'email': 'alice@example.com'},
    {'$set': {'age': 31}, '$push': {'logins': '2024-01-15'}}
)

Use it when

Applications already using MongoDB, document-oriented data (nested objects, variable schemas), rapid prototyping where schema flexibility matters, storing unstructured data like logs or events.

Skip it when

When you need strong ACID transactions across many documents (use PostgreSQL), when your data is highly relational, or when you want an ORM-style interface (use Motor + Beanie for async).

Alternatives
motorAsync MongoDB driver built on pymongo, for FastAPI/asyncio apps
mongoengineODM (ORM-like) layer on top of pymongo
beanieAsync ODM built on Motor, Pydantic integration

Ready to explore the full API?

See every class, function, and relationship in an interactive graph.