Connect Streamlit to MongoDB

This guide explains how to securely access a remote MongoDB database from Streamlit Cloud. It uses the PyMongo library and Streamlit's secrets management.



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:

use mydb
db.mycollection.insertMany([{"name" : "Mary", "pet": "dog"}, {"name" : "John", "pet": "cat"}, {"name" : "Robert", "pet": "bird"}])

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:

# .streamlit/secrets.toml

host = "localhost"
port = 27017
username = "xxx"
password = "xxx"


When copying your app secrets to Streamlit Cloud, be sure to replace the values of host, port, username, and password with those of your remote MongoDB database!

Add this file to .gitignore and don't commit it to your Github repo!

As the secrets.toml file above is not committed to Github, you need to pass its content to your deployed app (on Streamlit Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets Management.

Secrets manager screenshot

Add the PyMongo package to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed):

# requirements.txt

Copy the code below to your Streamlit app and run it. Make sure to adapt the name of your database and collection.


import streamlit as st
import pymongo

# Initialize connection.
# Uses st.experimental_singleton to only run once.
def init_connection():
    return pymongo.MongoClient(**st.secrets["mongo"])

client = init_connection()

# Pull data from the collection.
# Uses st.experimental_memo to only rerun when the query changes or after 10 min.
def get_data():
    db = client.mydb
    items = db.mycollection.find()
    items = list(items)  # make hashable for st.experimental_memo
    return items

items = get_data()

# Print results.
for item in items:
    st.write(f"{item['name']} has a :{item['pet']}:")

See st.experimental_memo above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.experimental_memo, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Read more about caching here.

If everything worked out (and you used the example data we created above), your app should look like this:

Finished app screenshot

Was this page helpful?

editSuggest edits

Still have questions?

Our forums are full of helpful information and Streamlit experts.