PyMongo
raw JSON → 4.16.0 verified Tue May 12 auth: no python install: verified quickstart: stale
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.
pip install pymongo Common errors
error AttributeError: 'Collection' object has no attribute 'insert' ↓
cause The `insert()` method was removed in PyMongo 4.0.0, along with `update()`, `remove()`, and `save()`, in favor of more explicit single- or multi-document operations.
fix
Replace
collection.insert(document) with collection.insert_one(document) for a single document, or collection.insert_many(documents_list) for multiple documents. Similarly, use update_one()/update_many() and delete_one()/delete_many() for update and delete operations. error AttributeError: 'Cursor' object has no attribute 'count' ↓
cause The `count()` method on both `Collection` and `Cursor` objects was deprecated in MongoDB 4.0 and removed in PyMongo 4.0. Attempting to use it on a Cursor in PyMongo 4.x will raise an AttributeError.
fix
Use
collection.count_documents(filter_query) for an accurate count, or collection.estimated_document_count() for a fast, approximate count of all documents in the collection (without a filter). error pymongo.errors.ConfigurationError: Server at localhost:27017 reports wire version X, but this version of PyMongo requires at least Y (MongoDB Z.0) ↓
cause This error occurs when the PyMongo driver version is incompatible with the connected MongoDB server version, typically when using a newer PyMongo version with an older MongoDB server.
fix
Upgrade your MongoDB server to a version compatible with your PyMongo driver (e.g., MongoDB 4.0+ for PyMongo 4.0+) or downgrade your PyMongo driver to a version compatible with your MongoDB server.
error AttributeError: 'InsertManyResult' object has no attribute 'inserted_count' ↓
cause The `InsertManyResult` object returned by `insert_many()` in PyMongo does not have an `inserted_count` attribute. This attribute was associated with older APIs or `BulkWriteResult`.
fix
To get the number of inserted documents from
insert_many(), use len(result.inserted_ids) instead. error TypeError: '_asyncio.Future' object is not subscriptable ↓
cause This error often occurs when using the `motor` (async PyMongo) driver and attempting to access the result of an asynchronous database operation (which returns a Future/coroutine) without `await`ing it first.
fix
Ensure that all asynchronous
motor operations are prefixed with await to retrieve their resolved value. For example, change doc = collection.find_one({}) to doc = await collection.find_one({}). Warnings
breaking collection.insert() removed in v4.0. Raises AttributeError. LLMs trained on pre-2022 data consistently generate insert() calls. ↓
fix insert_one({'key': 'value'}) or insert_many([{...}, {...}])
breaking collection.update() removed in v4.0. Raises AttributeError. ↓
fix update_one(filter, update) or update_many(filter, update)
breaking collection.remove() removed in v4.0. Raises AttributeError. ↓
fix delete_one(filter) or delete_many(filter)
breaking collection.count() removed in v4.0. Raises AttributeError. ↓
fix count_documents(filter) — note: count_documents({}) counts all docs. estimated_document_count() for fast approximate count.
breaking collection.save() removed in v4.0. ↓
fix insert_one() for new docs, replace_one(filter, doc, upsert=True) for upsert.
breaking collection.find_and_modify() removed in v4.0. ↓
fix find_one_and_update(), find_one_and_replace(), or find_one_and_delete()
gotcha mongodb+srv:// connection strings require dnspython. 'pip install pymongo' alone raises ConfigurationError. Install with pip install 'pymongo[srv]'. ↓
fix 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. ↓
fix Use Motor >= 3.6 with PyMongo >= 4.9. Or use native AsyncMongoClient (GA in 4.13) instead of Motor.
gotcha Python 3.8 dropped in PyMongo 4.11. Python 3.9 is now minimum. ↓
fix Use Python 3.9+
deprecated datetime.utcnow() pattern for MongoDB timestamps deprecated in Python 3.12. Use datetime.now(tz=timezone.utc) instead. ↓
fix from datetime import datetime, timezone; datetime.now(tz=timezone.utc)
gotcha Connecting with `mongodb+srv://` can fail with `ConfigurationError` if the SRV DNS record (e.g., `_mongodb._tcp.cluster.mongodb.net`) for the provided hostname does not exist (`NXDOMAIN`). This is an external DNS issue, not a missing dependency. ↓
fix Verify the `mongodb+srv` connection string hostname and ensure its corresponding SRV DNS record exists and is correctly configured with your DNS provider.
Install
pip install 'pymongo[srv]' Install compatibility verified last tested: 2026-05-12
python os / libc variant status wheel install import disk
3.10 alpine (musl) srv - - 0.29s 25.7M
3.10 alpine (musl) pymongo - - 0.29s 25.7M
3.10 slim (glibc) srv - - 0.21s 28M
3.10 slim (glibc) pymongo - - 0.21s 28M
3.11 alpine (musl) srv - - 0.45s 29.0M
3.11 alpine (musl) pymongo - - 0.45s 29.0M
3.11 slim (glibc) srv - - 0.37s 32M
3.11 slim (glibc) pymongo - - 0.36s 32M
3.12 alpine (musl) srv - - 0.63s 20.7M
3.12 alpine (musl) pymongo - - 0.61s 20.7M
3.12 slim (glibc) srv - - 0.57s 24M
3.12 slim (glibc) pymongo - - 0.57s 24M
3.13 alpine (musl) srv - - 0.59s 20.3M
3.13 alpine (musl) pymongo - - 0.61s 20.3M
3.13 slim (glibc) srv - - 0.56s 25M
3.13 slim (glibc) pymongo - - 0.55s 25M
3.9 alpine (musl) srv - - 0.26s 25.1M
3.9 alpine (musl) pymongo - - 0.25s 25.1M
3.9 slim (glibc) srv - - 0.22s 26M
3.9 slim (glibc) pymongo - - 0.23s 26M
Imports
- MongoClient wrong
collection.insert({'name': 'Alice'}) collection.update({'name': 'Alice'}, {'$set': {'age': 31}}) collection.remove({'name': 'Alice'}) collection.count()correctfrom 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) wrong
# Using motor for async — still valid but AsyncMongoClient is now native import motor.motor_asyncio client = motor.motor_asyncio.AsyncIOMotorClient('...')correctfrom 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 stale last tested: 2026-04-23
# 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()