Connect python to MongoDB service of AWS using lambda

Connect python to MongoDB service of AWS using lambda

Introduction

This guide outlines the process of connecting a Python application running in AWS Lambda to a MongoDB database hosted on MongoDB Atlas. It covers obtaining the MongoDB URI, installing the pymongo library, creating a Lambda layer, and deploying your main code in AWS Lambda—all tailored for Windows users.

Step 1: Create a MongoDB Atlas Account

  1. Visit MongoDB Atlas: Go to the MongoDB Atlas website.

  2. Sign Up/Login: Create a new account or log in if you already have one.

Step 2: Set Up a MongoDB Cluster

  1. Build a Cluster:

    • Click on the "Build a Cluster" button.

    • Select your preferred cloud provider and region. Choose the free tier for testing.

    • Click "Create Cluster". Wait for the cluster to be provisioned.

Step 3: Configure Network Access

  1. Network Access:

    • In the left sidebar, go to the "Network Access" tab.

    • Click on "Add IP Address."

    • To allow access from anywhere for testing, enter 0.0.0.0/0. Be cautious as this is not recommended for production.

    • Click "Confirm."

  2. Database Access:

    • Go to the "Database Access" tab.

    • Click on "Add New Database User."

    • Create a user with a username and password. Assign appropriate roles (e.g., Read and Write to any database).

    • Click "Add User."

Step 4: Get the MongoDB URI

  1. Obtain Connection String:

    • Go to the "Database Deployments" section.

    • Click "Connect" next to your cluster.

    • Choose "Connect your application."

    • Copy the provided connection string URI and replace <username> and <password> with your database user credentials:

        mongodb+srv://<username>:<password>@<cluster_name>.mongodb.net/test?retryWrites=true&w=majority
      

Step 5: Install Required Packages

To connect to MongoDB Atlas, you need to install the pymongo package.

  1. Open Command Prompt:

    • Launch the Command Prompt.
  2. Install Pymongo:

    • Run the following command:

        pip install pymongo
      

Step 6: Compress the Package for Lambda

AWS Lambda requires a zip file containing the necessary libraries.

  1. Create Layer Directory:

    • Create a new directory for the Lambda layer:

        mkdir pymongo-layer
        cd pymongo-layer
      
  2. Set Up Virtual Environment:

    • Create a virtual environment:

        python -m venv venv
      
  3. Activate Virtual Environment:

    • Activate the virtual environment:

        venv\Scripts\activate
      
  4. Install Pymongo Again:

    • Inside the activated environment, install pymongo:

        pip install pymongo
      
  5. Prepare Package for Lambda:

    • Create the necessary directory structure:

        mkdir -p python/lib/python3.8/site-packages
      
    • Copy the installed packages into this directory:

        xcopy /s venv\Lib\site-packages\* python\lib\python3.8\site-packages\
      
    • Compress the directory into a zip file:

        powershell -command "Compress-Archive -Path python -DestinationPath pymongo-layer.zip"
      

Now, you have pymongo-layer.zip ready for upload to AWS Lambda.

AWS Lambda Setup

Step 1: Create a Lambda Layer for Pymongo

  1. Access AWS Lambda:

    • Open the AWS Management Console and navigate to the Lambda service.
  2. Create Layer:

    • In the left sidebar, go to Layers and click on "Create Layer."

    • Upload the pymongo-layer.zip file.

    • Select the appropriate runtime (e.g., Python 3.8).

    • Click "Create."

Step 2: Create a Lambda Function

  1. Create New Function:

    • Return to the AWS Lambda console.

    • Click "Create function."

    • Select "Author from scratch."

    • Fill in the details:

      • Function name: MongoDBConnectionFunction

      • Runtime: Python 3.8

      • Permissions: Choose an execution role with basic Lambda permissions or create a new one.

  2. Create Function:

    • Click "Create function." You will be redirected to the function configuration page.

Python Connection Code

  1. Code Implementation:

    • Scroll down to the Function code section in the AWS Lambda console.

    • Copy and paste the following code into the code editor:

import json
import pymongo
import os

def lambda_handler(event, context):
    # MongoDB connection string from environment variables
    mongo_uri = os.getenv('MONGO_URI')

    # Connect to MongoDB
    client = pymongo.MongoClient(mongo_uri)

    # Select database and collection
    db = client['your_database_name']  # Replace with your database name
    collection = db['your_collection_name']  # Replace with your collection name

    # Example: Insert a document
    document = {
        "name": "Sample Document from Lambda",
        "type": "Demo"
    }
    result = collection.insert_one(document)

    # Example: Query the inserted document
    inserted_document = collection.find_one({"_id": result.inserted_id})

    return {
        'statusCode': 200,
        'body': json.dumps(f'Document inserted: {inserted_document}')
    }

Note

Make sure to replace your_database_name and your_collection_name with the actual names from your MongoDB Atlas setup.

Deploying the Code to Lambda

  1. Set Environment Variables:

    • In the Environment variables section, add a new variable:

      • Key: MONGO_URI

      • Value: Your MongoDB Atlas connection string (the URI you copied earlier).

  2. Attach Layer:

    • In the Layers section, click on "Add a layer," and select the pymongo layer you created earlier.
  3. Deploy Function:

    • Click on "Deploy" to save your changes.

Testing the Lambda Function

  1. Create Test Event:

    • Click on the "Test" button in the AWS Lambda console.

    • Configure a test event using the default settings.

  2. Invoke Function:

    • Click on "Test" to invoke the Lambda function.

    • Check the "Execution result" to confirm the document has been successfully inserted and retrieved from MongoDB.

Conclusion

This documentation provides a comprehensive guide for Windows users on connecting a Python application running in AWS Lambda to a MongoDB Atlas database. By following these steps, you will successfully deploy a serverless application capable of performing various database operations.

Feel free to modify any sections to better fit your specific project requirements!