Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

MongoDB

To set up a MongoDB cluster, these steps will help you on the way (subject to changes):

  • Navigate to MongoDB.com

  • Create an account

  • Choose the Free tier

  • Create a separate database username and password (Security -> Database & Network Access -> Database Users)

  • Edit IP Acess List in the same page adding 0.0.0.0/0 to the list (catch-all)

  • From the Project Overview choose Connect New in the Application Development and choose Drivers and Client Libraries, then Python + PyMongo (Synchronous) and check Get/Configure connection string and Installation instructions

Limitation of Free tier

  • 512 MB storage

  • 10 GB upload and download per 7 days (rolling)

Check connection

Accessing and manipulating

Inserting

  • The MongoDB structure is such that each database contains collections.

  • These collections contain documents, which are similar to dictionaries.

  • Thus, when inserting data, we use dictionaries.

Check existence of record

Reading

Updating

  • Updating documents is done using the update_one and update_many methods.

  • The first argument is a query that selects the documents to update.

  • The second argument is a dictionary that specifies the changes.

Aggregating

  • Combine multiple operations into a single query.

Accessing through Streamlit

  • Several ways are possible.

  • The Python code below assumes a secrets.toml with a [mongo] section.

    • Exchange khliland, ind320, rhc2o, IND320, example and data with your equivalent data.

    • Exchange “+PWD+” with the actual password.

    • Copy to streamlit.io when deploying.

[mongo]
uri = "mongodb+srv://khliland:"+PWD+"@ind320.rhc2o.mongodb.net/?retryWrites=true&w=majority&appName=IND320"
# mongodb.py
import streamlit as st
import pymongo

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

client = init_connection()

# Pull data from the collection.
# Uses st.cache_data to only rerun when the query changes or after 10 min.
@st.cache_data(ttl=600)
def get_data():
    db = client['example']
    collection = db['data']
    items = collection.find()
    items = list(items)
    return items

items = get_data()

# Print results.
for item in items:
    st.write(f"{item['name']} is {item['age']} years old")

Deleting

  • Deleting documents is done using the delete_one and delete_many methods.