PyMongo
Official MongoDB Python driver. Synchronous client for MongoDB. v4.0 removed all APIs deprecated in v3.x — insert(), update(), remove(), count(), save() all gone. Current version: 4.16.0 (Mar 2026). Python 3.9+ required (3.8 dropped in v4.11). AsyncMongoClient added as GA in v4.13. Most LLM-generated pymongo code uses v3 patterns that break on v4.
Warnings
- breaking collection.insert() removed in v4.0. Raises AttributeError. LLMs trained on pre-2022 data consistently generate insert() calls.
- breaking collection.update() removed in v4.0. Raises AttributeError.
- breaking collection.remove() removed in v4.0. Raises AttributeError.
- breaking collection.count() removed in v4.0. Raises AttributeError.
- breaking collection.save() removed in v4.0.
- breaking collection.find_and_modify() removed in v4.0.
- gotcha mongodb+srv:// connection strings require dnspython. 'pip install pymongo' alone raises ConfigurationError. Install with pip install 'pymongo[srv]'.
- gotcha Motor (async MongoDB) and PyMongo >= 4.9 version coupling. Motor < 3.6 is incompatible with PyMongo >= 4.9. Mixing versions causes ImportError or unexpected behavior.
- gotcha Python 3.8 dropped in PyMongo 4.11. Python 3.9 is now minimum.
- deprecated datetime.utcnow() pattern for MongoDB timestamps deprecated in Python 3.12. Use datetime.now(tz=timezone.utc) instead.
Install
-
pip install pymongo -
pip install 'pymongo[srv]'
Imports
- MongoClient
from pymongo import MongoClient client = MongoClient('mongodb+srv://user:pass@cluster.mongodb.net/') db = client['mydb'] collection = db['users'] # Insert result = collection.insert_one({'name': 'Alice', 'age': 30}) print(result.inserted_id) # Find doc = collection.find_one({'name': 'Alice'}) # Update collection.update_one({'name': 'Alice'}, {'$set': {'age': 31}}) # Count count = collection.count_documents({'age': {'$gt': 18}}) # Delete collection.delete_one({'name': 'Alice'}) - AsyncMongoClient (v4.13+ GA)
from pymongo import AsyncMongoClient import asyncio async def main(): client = AsyncMongoClient('mongodb+srv://user:pass@cluster.mongodb.net/') db = client['mydb'] result = await db['users'].insert_one({'name': 'Alice'}) print(result.inserted_id) await client.close() asyncio.run(main())
Quickstart
# pip install 'pymongo[srv]'
from pymongo import MongoClient
client = MongoClient('mongodb+srv://user:pass@cluster.mongodb.net/')
db = client['mydb']
col = db['users']
# Insert
col.insert_one({'name': 'Alice', 'age': 30})
# Find
for doc in col.find({'age': {'$gt': 18}}):
print(doc)
# Update
col.update_one({'name': 'Alice'}, {'$set': {'age': 31}})
# Count
print(col.count_documents({}))
# Delete
col.delete_one({'name': 'Alice'})
client.close()