4.6 KiB
MongoDB Python Client Guide
This guide explains how to install the necessary Python packages and use the provided example script to connect to your MongoDB instance.
Prerequisites
- Python 3.6 or higher
- pip (Python package manager)
- Access to your MongoDB instance (running in Docker or elsewhere)
Installation Instructions
-
Install the PyMongo package
PyMongo is the official MongoDB driver for Python. Install it using pip:
pip install pymongoIf you're using a virtual environment (recommended):
# Create a virtual environment python -m venv venv # Activate the virtual environment # On Linux/macOS: source venv/bin/activate # On Windows: venv\Scripts\activate # Install PyMongo pip install pymongo -
Configure environment variables (optional)
The example script uses environment variables for configuration. You can set them in your shell:
export MONGO_HOST="your-mongodb-host" export MONGO_PORT="27017" export MONGO_USERNAME="admin" export MONGO_PASSWORD="your-password" export MONGO_AUTH_DB="admin"Alternatively, you can modify the default values directly in the script.
Using the Example Script
The python_example.py script demonstrates basic MongoDB operations:
- Connecting to MongoDB with authentication
- Listing available databases
- Creating a sample database and collection
- Inserting sample data
- Querying the data
Running the Script
python python_example.py
Expected Output
🔄 Connecting to MongoDB...
✅ Successfully connected to MongoDB at localhost:27017
📚 Available databases:
- admin
- config
- local
🔄 Creating sample data...
✅ Successfully inserted 3 documents into sample_db.users
📊 Total documents in users: 3
🔄 Querying data...
🔍 All users:
- John Doe (john.doe@example.com), Age: 30
- Jane Smith (jane.smith@example.com), Age: 25
- Bob Johnson (bob.johnson@example.com), Age: 35
🔍 Users older than 30:
- Bob Johnson (bob.johnson@example.com), Age: 35
👋 Connection closed
Modifying the Script for Your Needs
Connecting to Your MongoDB Instance
Update the connection parameters at the top of the script:
MONGO_HOST = "your-mongodb-host" # Replace with your MongoDB host IP
MONGO_PORT = 27017
MONGO_USERNAME = "admin" # Replace with your MongoDB username
MONGO_PASSWORD = "your-password" # Replace with your MongoDB password
MONGO_AUTH_DB = "admin"
Creating Your Own Collections and Queries
The example script provides a template that you can modify:
- To create a different collection, modify the
create_sample_datafunction - To perform different queries, modify the
query_datafunction
Common MongoDB Operations in Python
Insert a Document
result = collection.insert_one({"name": "Alice", "age": 29})
print(f"Inserted document ID: {result.inserted_id}")
Find Documents
# Find one document
user = collection.find_one({"name": "John Doe"})
print(user)
# Find documents with a filter
users = collection.find({"age": {"$gt": 25}})
for user in users:
print(user)
Update Documents
# Update one document
result = collection.update_one(
{"name": "John Doe"},
{"$set": {"age": 31}}
)
print(f"Modified {result.modified_count} document(s)")
# Update multiple documents
result = collection.update_many(
{"age": {"$lt": 30}},
{"$inc": {"age": 1}}
)
print(f"Modified {result.modified_count} document(s)")
Delete Documents
# Delete one document
result = collection.delete_one({"name": "John Doe"})
print(f"Deleted {result.deleted_count} document(s)")
# Delete multiple documents
result = collection.delete_many({"age": {"$lt": 25}})
print(f"Deleted {result.deleted_count} document(s)")
Troubleshooting
Connection Issues
If you can't connect to MongoDB:
-
Verify that your MongoDB container is running:
docker-compose ps -
Check if you can reach MongoDB from your host:
telnet your-mongodb-host 27017 -
Ensure your MongoDB credentials are correct
Authentication Errors
If you see authentication errors:
- Verify your username and password
- Make sure you're using the correct authentication database (usually "admin")
- Check if MongoDB is configured with authentication enabled