Database Management with Python, Streamlit & MongoDB
Learn to manage databases effortlessly with Python, Streamlit, and MongoDB, creating dynamic and user-friendly solutions!
Integrating MongoDB Database Management into your Streamlit application can provide easy access to database content. Whether you're building a login, signup functionality or any full stack application using Streamlit, or just want to create a authorization layer into your application, this step-by-step guide will help you seamlessly incorporate DB management into your Streamlit app using the Python language.
Step 1. Create a virtual environment
- Create a folder and open it in your Code editor like VS Code, PyCharm, etc.
- Open a terminal or powershell or command prompt.
- Write the below command to build & activate your virtual python environment.
build_virtual_env
python -m venv myenv
activate_virtual_env
.\myenv\Scripts\activate
- If there will be any error occurs, related to `ExecutionPolicy` during activation of virtual environment, run the below command. Otherwise, skip this command.
execution_policy_error_resolved
Set-ExecutionPlicy -Scope Process -ExecutionPolicy Bypass
- To deactivate your python virtual environment.
deactivate_virtual_env
deactivate
Step 2. Install required dependencies
Next, you need to install all the required dependencies to setup this db management. All the required dependencies are listed below:
- Streamlit
- PyMongo
- Pandas
Run the below command in your shell to install all these dependencies,
install_dependencies
pip install streamlit pymongo pandas
Step 3. Setting up MongoDB
Before we start building our database management app, we need a MongoDB database to work with. You can either set it up locally or use MongoDB Atlas, which is MongoDB’s free cloud-hosted solution. I recommend Atlas for beginners because it’s quick, secure, and doesn’t require you to run MongoDB on your machine.
1. Go to MongoDB Atlas and sign up (you can use your Google or GitHub account).
2. Click "Build a Cluster" → choose the free M0 Sandbox plan.
3. Select your preferred cloud provider (AWS, GCP, or Azure) and region (closer to your location = faster performance).
4. Create a new database user and password.
5. In Network Access, allow access from your IP (Add Current IP Address
) or 0.0.0.0/0
for development.
6. Once the cluster is ready, click "Connect" → choose "Connect your application" → copy the connection string (it will look like this):
MongoDB URI
mongodb+srv://<username>:<password>@cluster0.mongodb.net/
Store your connection string securely in an environment variable (we’ll use it later in Python) instead of hardcoding it.
Use.streamlit/secrets.toml
file to use the confidential credentials in streamlit.
Step 4. Connecting Python to MongoDB
Now that our MongoDB database is ready, it’s time to connect it to our Python application.
We’ll use PyMongo, the official Python driver for MongoDB.
Create a file named mongodb.py
and add the following code:
mongodb.py
from pymongo import MongoClient
import streamlit as st
def URI_Exist():
if st.secrets["MONGODB_URI"] != "":
return True
return False
def create_connection():
if URI_Exist():
MONGODB_URI = st.secrets["MONGODB_URI"]
else:
MONGODB_URI = "mongodb://localhost:27017/"
client = MongoClient(MONGODB_URI)
db = client['user_db'] # user_db is the name of the db collection
return db
To test the mongodb is connected or not. You need to call create_connection()
function and add any logs.
Step 5. Creating the Streamlit App Structure
With our MongoDB connection ready, it’s time to build the frontend of our database management app using Streamlit. Streamlit makes it super easy to create interactive web apps directly from Python — no need to write HTML, CSS, or JavaScript manually.
Let’s create a file named app.py
and set up a simple layout:
app.py
import streamlit as st
from mongodb import create_connection
st.title("📦 MongoDB Management App")
st.write("Easily manage your MongoDB collections with a simple interface.")
menu = ["Create", "Read", "Update", "Delete"]
choice = st.sidebar.selectbox("Select Operation", menu)
if choice == "Create":
st.subheader("Add a New Record")
elif choice == "Read":
st.subheader("View Records")
elif choice == "Update":
st.subheader("Update an Existing Record")
elif choice == "Delete":
st.subheader("Delete a Record")
To Run the App
terminal
streamlit run app.py
Your browser will open a new tab with your Streamlit app running at http://localhost:8501
.
Step 6. Implementing CRUD Operations
CRUD stands for Create, Read, Update, and Delete — the four fundamental operations for working with databases. We’ll now add functionality to each menu option in our Streamlit app to manage MongoDB records directly from the browser.
Create — Add a New Record
We’ll take user input and insert it into the MongoDB collection:
choice_create
if choice == "Create":
st.subheader("Add a New Record")
name = st.text_input("Enter Name")
email = st.text_input("Enter Email")
if st.button("Add User"):
if name and email:
collection.insert_one({"name": name, "email": email})
st.success(f"User {name} added successfully!")
else:
st.warning("Please fill in all fields.")
Read — View Records
We’ll fetch all documents from MongoDB and display them in a table:
choice_read
elif choice == "Read":
st.subheader("View Records")
users = list(collection.find({}, {"_id": 0})) # Hide _id
if users:
st.dataframe(users)
else:
st.info("No records found.")
Update — Edit an Existing Record
We’ll let users select a record, edit the fields, and update MongoDB:
choice_update
elif choice == "Update":
st.subheader("Update an Existing Record")
users = list(collection.find({}, {"_id": 0}))
if users:
selected_user = st.selectbox("Select User", [user["name"] for user in users])
user_data = collection.find_one({"name": selected_user})
new_name = st.text_input("Name", value=user_data["name"])
new_email = st.text_input("Email", value=user_data["email"])
if st.button("Update User"):
collection.update_one({"name": selected_user}, {"$set": {"name": new_name, "email": new_email}})
st.success(f"User {selected_user} updated successfully!")
else:
st.info("No records to update.")
Delete — Remove a Record
We’ll allow users to select and delete a record from the database:
choice_delete
elif choice == "Delete":
st.subheader("Delete a Record")
users = list(collection.find({}, {"_id": 0}))
if users:
selected_user = st.selectbox("Select User to Delete", [user["name"] for user in users])
if st.button("Delete User"):
collection.delete_one({"name": selected_user})
st.success(f"User {selected_user} deleted successfully!")
else:
st.info("No records to delete.")
How it works:
insert_one()
→ Adds a new document to MongoDB.find()
→ Retrieves all documents.update_one()
→ Modifies an existing document.delete_one()
→ Removes a document.
Conclusion
With just a few lines of Python, we transformed a plain database into a fully functional web application where users can add, view, edit, and delete data in real time — all through a clean and intuitive UI.
The beauty of this approach is its flexibility:
- You can adapt the app to manage any kind of data.
- Add authentication for security.
- Deploy it on Streamlit Cloud or any hosting platform.
This project is a great starting point for building custom admin dashboards, internal tools, or learning how to integrate databases with web apps.
Now it’s your turn — tweak the UI, experiment with new features, and make it your own! 🚀
Comments