<aside> ⚠️ DEPRECATED!!! This guide migrated to our docs. Please view the current version at: https://docs.streamlit.io/en/stable/tutorial/mongodb.html
</aside>
This guide explains how to securely access a MongoDB database from Streamlit sharing or Streamlit for Teams. It uses the PyMongo library and Streamlit's secrets management (requires streamlit v0.80.0 or higher).
<aside> 🏃 If you already have a database that you want to use, feel free to skip this step.
</aside>
First, follow the official tutorials to install MongoDB, set up authentication (note down the username and password!), and connect to the database. Once you are connected (with mongo
), 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 dir. Create this file if it doesn't exist yet and add the database information as shown below:
# .streamlit/secrets.toml
[mongo]
host = "localhost"
port = 27017
username = "xxx"
password = "xxx"
<aside>
☝ Add this file to .gitignore
and don't commit it to your Github repo!
</aside>
As the secrets.toml
file above is not commited to Github, you need to pass its content to your deployed app (on Streamlit sharing or Streamlit for Teams) 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 infos in Secrets Management.
pip install pymongo
Add the package to your requirements.txt
file, preferably pinning its version (just replace x.x.x
with the version you installed):
# requirements.txt
pymongo==x.x.x
Copy the code below to your Streamlit app and run it. Make sure to adapt the name of your database and collection.