Back to Blog
Python

Python PyMongo: Connect to MongoDB and Basic CRUD

python pymongo connect mongodb and basic crud: This article explains how to connect to MongoDB from Python using PyMongo and perform basic CRUD operations, including i...

PyMongoMongoDBCRUDPythonDatabase
Python code connecting to MongoDB using PyMongo for basic CRUD operations

python pymongo connect mongodb and basic crud requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.

To connect to MongoDB from Python using PyMongo and perform basic CRUD operations, you need the official MongoDB driver for Python. PyMongo provides a synchronous API that maps closely to the MongoDB query language, making it straightforward to insert, read, update, and delete documents once the connection is established.

Connecting to MongoDB with PyMongo

Install PyMongo with pip:

pip install pymongo

Then 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 is lazy; it does not attempt to connect until the first operation is executed. This means a misconfigured host will not raise an error until you run a command.

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 or the connection string is invalid, PyMongo raises a ServerSelectionTimeoutError. 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.

python pymongo connect mongodb and basic crud: Practical Usa | RYUSLOG DEV