mongo-service/PYTHON_README.md

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

  1. Install the PyMongo package

    PyMongo is the official MongoDB driver for Python. Install it using pip:

    pip install pymongo
    

    If 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
    
  2. 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:

  1. Connecting to MongoDB with authentication
  2. Listing available databases
  3. Creating a sample database and collection
  4. Inserting sample data
  5. 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:

  1. To create a different collection, modify the create_sample_data function
  2. To perform different queries, modify the query_data function

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:

  1. Verify that your MongoDB container is running:

    docker-compose ps
    
  2. Check if you can reach MongoDB from your host:

    telnet your-mongodb-host 27017
    
  3. Ensure your MongoDB credentials are correct

Authentication Errors

If you see authentication errors:

  1. Verify your username and password
  2. Make sure you're using the correct authentication database (usually "admin")
  3. Check if MongoDB is configured with authentication enabled

Further Resources