Connect Streamlit to MongoDB
Introduction
This guide explains how to securely access a MongoDB database from Streamlit Cloud. It uses the PyMongo library and Streamlit's secrets management.
Create a MongoDB Database
If you already have a database that you want to use, feel free
to skip to the next step.
First, follow the official tutorials to install MongoDB, set up authentication (note down the username and password!), and connect to the MongoDB instance. Once you are connected, open the mongo shell and enter the following two commands to create a collection with some example values:
sql
use mydb
db.mycollection.insertMany([{"name" : "Mary", "pet": "dog"}, {"name" : "John", "pet": "cat"}, {"name" : "Robert", "pet": "bird"}])
Add username and password to your local app secrets
Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the database information as shown below:
