<aside> ⚠️ DEPRECATED!!! This guide migrated to our docs. Please view the current version at: https://docs.streamlit.io/en/stable/tutorial/mongodb.html

</aside>

Introduction

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).

Step 1: Create a MongoDB database

<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"}])

Step 2: 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 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>

Step 3: Copy your app secrets to the cloud

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.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/24e1199d-f19e-40c6-b4f5-c0f4598556de/Screenshot_2021-05-04_at_19.01.58.png

Step 4: Install PyMongo and add it to your requirements file

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

Step 5: Write your Streamlit app

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