Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~3 min readPython
#PyMongo#MongoDB#CRUD#Python
Python code connecting to MongoDB using PyMongo for basic CRUD operations

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:

bash
pip install pymongo

Then create a MongoClient instance with a connection string. The default local MongoDB server is accessible at mongodb://localhost:27017/:

python
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:

python
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:

python
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:

python
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:

python
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:

python
doc = collection.find_one({"name": "Alice"}) print(doc)

If no document matches, find_one returns None. To retrieve multiple documents, use find:

python
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:

python
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:

python
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:

python
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:

python
result = collection.delete_one({"name": "Alice"}) print(result.deleted_count)

For all matching documents, use delete_many:

python
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:

python
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:

python
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:

python
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 tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.