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
- MongoDB Atlas Cluster: Ensure you have a cluster running and a connection string.
- AWS Account: Access to AWS Lambda and IAM roles.
- Python Environment: Familiarity with Python and PyMongo.
- IAM Role with VPC Access (Optional for secure access).
- 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
- Login to AWS Console → Go to AWS Lambda → Click Create Function.
- 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.
- Click Create Function.
Lambda doesn't have PyMongo by default, so you need to package it.
- Locally create a folder and install PyMongo:
- Zip the contents:
- Go back to AWS Lambda.
- Under the Function Code section, choose Upload from .zip file.
- Upload the
pymongo_lambda.zip
file.
Replace the auto-generated handler code with the following:
- Scroll to the Configuration tab and select Environment Variables.
- Add a new key:
- Key:
MONGODB_URI
- Value: Your MongoDB connection URI.
- Click Test and configure a test event (can be empty or a basic JSON).
- Run the test to see the success response: