Skip to main content

Command Palette

Search for a command to run...

Connecting Python to AWS MongoDB Service Using Lambda

Published
3 min read

In this blog, we will explore how to connect Python to the MongoDB service provided by AWS, specifically using AWS Lambda. This setup is particularly useful for creating serverless applications that need to interact with a database.

Prerequisites

Before we get started, ensure you have the following:

  1. AWS Account: You need an AWS account to create resources.

  2. MongoDB Database: Set up your MongoDB instance on AWS, either using Amazon DocumentDB (with MongoDB compatibility) or MongoDB Atlas.

  3. AWS Lambda: Familiarity with AWS Lambda and its interface in the AWS Management Console.

Step 1: Set Up Your MongoDB Database

If you haven’t already, set up your MongoDB instance:

  • For Amazon DocumentDB:

  • Create a new DocumentDB cluster from the AWS Management Console.

  • Note down the connection string and credentials.

  • For MongoDB Atlas:

  • Create a new project and a cluster.

  • Whitelist your IP address and note the connection string.

Step 2: Create a Lambda Function

  1. Go to AWS Lambda in the AWS Management Console.

  2. Click on Create function.

  3. Choose Author from scratch:

  • Name your function (e.g., MongoDBLambdaFunction).

  • Select Python 3.x as the runtime.

Click on Create function.

Step 3: Configure the Lambda Function

  1. In the Function code section, you will write the Python code to connect to MongoDB.

  2. Add necessary libraries. Since AWS Lambda has a limitation on package sizes, you might want to use a deployment package or AWS Lambda Layers to include the pymongo library.

import pymongo
import os

def lambda_handler(event, context):
    # MongoDB connection string
    mongo_uri = os.getenv('MONGO_URI')  # Set this in your Lambda environment variables

    # Connect to MongoDB
    client = pymongo.MongoClient(mongo_uri)
    db = client['your_database_name']  # Replace with your database name

    # Example: Fetch data from a collection
    collection = db['your_collection_name']  # Replace with your collection name
    data = collection.find_one()  # Fetch one document

    return {
        'statusCode': 200,
        'body': data
    }

Step 4: Set Environment Variables

  1. In your Lambda function configuration, navigate to the Configuration tab.

  2. Click on Environment variables and add a new variable:

  • Key: MONGO_URI

  • Value: Your MongoDB connection string.

Step 5: Test Your Lambda Function

  1. Click on Test in the Lambda function console.

  2. Create a test event (the content of the event won’t matter for this simple connection test).

  3. Run the test and check the output.

Conclusion

You have successfully set up a Python Lambda function to connect to your MongoDB service on AWS! This setup allows you to interact with your database in a serverless environment, making it easier to scale and manage.

For more detailed instructions on AWS Lambda and MongoDB integrations, check out the AWS documentation and MongoDB documentation.

More from this blog

Amazon S3 Storage Classes

43 posts