AWS Logo
Menu

Connecting MongoDB Atlas with AWS Lambda Using PyMongo

Learn how to integrate MongoDB Atlas with AWS Lambda using PyMongo in this step-by-step guide. Build serverless apps that are fast, reliable, and scalable—no server maintenance required!

Published Nov 28, 2024

Prerequisites

  1. MongoDB Atlas Cluster: Ensure you have a cluster running and a connection string.
  2. AWS Account: Access to AWS Lambda and IAM roles.
  3. Python Environment: Familiarity with Python and PyMongo.
  4. IAM Role with VPC Access (Optional for secure access).

Steps

1. Set Up MongoDB Atlas Cluster

  • Go to MongoDB Atlas and create a new cluster.
  • Whitelist your IP or set to allow all (0.0.0.0/0) for testing.
  • Obtain the connection string (URI), e.g.:mongodb+srv://<username>:<password>@cluster0.mongodb.net/myDatabase?retryWrites=true&w=majority

2. Create an AWS Lambda Function

  1. Login to AWS Console → Go to AWS Lambda → Click Create Function.
  2. Choose Author from Scratch and configure:
    • Name: MongoDBAtlasLambda
    • Runtime: Python 3.x
    • Role: Choose an existing role or create a new one with basic Lambda permissions.
  3. Click Create Function.

3. Add PyMongo Dependency

Lambda doesn't have PyMongo by default, so you need to package it.
  • Locally create a folder and install PyMongo:
  • Zip the contents:

4. Upload Deployment Package

  1. Go back to AWS Lambda.
  2. Under the Function Code section, choose Upload from .zip file.
  3. Upload the pymongo_lambda.zip file.

5. Write the Lambda Function Code

Replace the auto-generated handler code with the following:

6. Add Environment Variables

  1. Scroll to the Configuration tab and select Environment Variables.
  2. Add a new key:
    • Key: MONGODB_URI
    • Value: Your MongoDB connection URI.

7. Test Your Lambda Function

  1. Click Test and configure a test event (can be empty or a basic JSON).
  2. Run the test to see the success response:
 

Comments