Python PyMongo: Connect to MongoDB and Basic CRUD
Learn how to use PyMongo to connect to MongoDB and perform basic CRUD operations: insert, find, update, and delete documents with code examples.

PyMongo is the official MongoDB driver for Python. It provides a synchronous API that maps closely to the MongoDB query language, so you can connect to a MongoDB server and insert, read, update, and delete documents with straightforward Python calls.
Connecting to MongoDB with PyMongo
Install PyMongo with pip:
pip install pymongoThen create a MongoClient instance with a connection string. The default local MongoDB server is accessible at mongodb://localhost:27017/:
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")The connection string can include authentication credentials, replica set information, and other options. For example, a connection with a username and password looks like:
client = MongoClient("mongodb://user:password@host:port/")MongoClient does not wait for a successful connection when it is created. If the host is unreachable, the error usually appears when you run a command such as ping or a query.
Accessing a Database and Collection
Once the client is available, you can access a database and a collection using dictionary-style access:
db = client["mydatabase"]
collection = db["mycollection"]Both the database and the collection are created lazily when the first document is inserted. You can also use attribute access (client.mydatabase.mycollection) as long as the names are valid Python identifiers.
Creating Documents (Insert)
To insert a single document, use insert_one:
document = {"name": "Alice", "age": 30}
result = collection.insert_one(document)
print(result.inserted_id)insert_one returns an InsertOneResult whose inserted_id attribute contains the _id of the inserted document. If the document does not include an _id field, PyMongo generates one automatically.
For multiple documents, use insert_many with a list:
documents = [
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35},
]
result = collection.insert_many(documents)
print(result.inserted_ids)The inserted_ids attribute is a list of the inserted document IDs.
Reading Documents (Find)
Use find_one to retrieve a single document matching a query filter:
doc = collection.find_one({"name": "Alice"})
print(doc)If no document matches, find_one returns None. To retrieve multiple documents, use find:
for doc in collection.find({"age": {"$gt": 20}}):
print(doc)find returns a cursor that iterates over matching documents. You can add projections, sorting, and limits directly in the query:
for doc in collection.find({"age": {"$gt": 20}}).sort("age", -1).limit(10):
print(doc)Updating Documents
To modify existing documents, use update_one or update_many. The first argument is the filter, and the second is the update operation. The $set operator updates or creates the specified fields:
result = collection.update_one(
{"name": "Alice"},
{"$set": {"age": 31}}
)
print(result.modified_count)modified_count tells you how many documents were actually changed. If the filter matches no document, modified_count is 0. To update all documents that match the filter, use update_many:
result = collection.update_many(
{"age": {"$lt": 30}},
{"$inc": {"age": 1}}
)
print(result.modified_count)Deleting Documents
Use delete_one to remove the first document that matches the filter:
result = collection.delete_one({"name": "Alice"})
print(result.deleted_count)For all matching documents, use delete_many:
result = collection.delete_many({"age": {"$lt": 30}})
print(result.deleted_count)The deleted_count attribute reports how many documents were removed.
Handling Connection Errors and Failures
When the MongoDB server is unreachable, PyMongo raises ServerSelectionTimeoutError. Malformed connection strings can raise ConfigurationError when the client is created. You can catch connection-related exceptions from pymongo.errors:
from pymongo.errors import ConnectionFailure
try:
client.admin.command("ping")
except ConnectionFailure as exc:
print(f"Could not connect to MongoDB: {exc}")The ping command is a lightweight way to verify that the server is reachable. Authentication failures raise OperationFailure instead, which you can also catch if needed.
Operational Considerations for Production Use
For production workloads, avoid creating a new MongoClient for every operation. PyMongo maintains a connection pool per client, so reuse the same client across your application. Using a with block is a convenient way to ensure the client is closed when it is no longer needed:
with MongoClient("mongodb://localhost:27017/") as client:
db = client["mydatabase"]
collection = db["mycollection"]
collection.insert_one({"name": "Dave", "age": 40})The with block closes the client and releases its resources when the block exits. This is especially useful in short-lived scripts or functions.
When querying frequently, create indexes on the fields used in filters to avoid collection scans. For example, to index the name field:
collection.create_index("name")For bulk inserts, prefer insert_many over repeated insert_one calls to reduce round trips. Similarly, use update_many and delete_many when the operation applies to multiple documents.
PyMongo is thread-safe, so a single client can be shared across threads. The driver handles connection pooling and retry logic internally. Always ensure that the client is closed gracefully when the application shuts down to avoid leaking connections.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.