AWS Builder Center

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!

AWS Community Builder | 3x AWS Certified Educator | AWS UG Ahm Lead | Speaker | Solution Architect |



Prerequisites

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



Steps

1. Set Up MongoDB Atlas Cluster

  • 
  • Whitelist your IP or set to allow all ( 0.0.0.0/0 ) for testing.
mongodb+srv://<username>:<password>@cluster0.mongodb.net/myDatabase?retryWrites=true&w=majority

  • 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.
  1. 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.
  1. 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:
mkdir pymongo_lambda && cd pymongo_lambda
pip install pymongo -t .
  • Zip the contents:
zip -r pymongo_lambda.zip .


4. Upload Deployment Package

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

5. Write the Lambda Function Code

Replace the auto-generated handler code with the following:
import pymongo
import os

def lambda_handler(event, context):
# Connection string from MongoDB Atlas
uri = os.getenv('MONGODB_URI', 'your-default-uri-here')

# Connect to the client
client = pymongo.MongoClient(uri)

# Choose the database and collection
db = client['myDatabase']
collection = db['myCollection']

# Example operation: Insert a document
doc = {"message": "Hello from AWS Lambda!", "source": "Lambda"}
result = collection.insert_one(doc)

return {
'statusCode': 200,
'body': f'Document inserted with ID: {result.inserted_id}'
}


6. Add Environment Variables

  1. Scroll to the Configuration tab and select Environment Variables.
  1. 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).
  1. Run the test to see the success response:
{
"statusCode": 200,
"body": "Document inserted with ID: <inserted_id>"
}


Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article