In [71]:
! docker pull mongodb/mongodb-community-server:latest
! docker run --name mongodb -p 27017:27017 -d mongodb/mongodb-community-server:latest
latest: Pulling from mongodb/mongodb-community-server
Digest: sha256:0183a67a4899d75b1b38a3c33da689641d50e98b7e2e45a067b06f853115c00a
Status: Image is up to date for mongodb/mongodb-community-server:latest
docker.io/mongodb/mongodb-community-server:latest

What's next:
    View a summary of image vulnerabilities and recommendations → docker scout quickview mongodb/mongodb-community-server:latest
fed31366c8c3e142975c30c25c760502c090c5b3ea9881204f6ae228050386c1
In [72]:
!docker ps
CONTAINER ID   IMAGE                                     COMMAND                  CREATED        STATUS                  PORTS                      NAMES
fed31366c8c3   mongodb/mongodb-community-server:latest   "python3 /usr/local/…"   1 second ago   Up Less than a second   0.0.0.0:27017->27017/tcp   mongodb
In [73]:
# create database
!docker exec -it mongodb mongosh --eval 'db = db.getSiblingDB("test_db"); db.createCollection("test_collection")'
]0;mongosh mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017

What's next:
    Try Docker Debug for seamless, persistent debugging tools in any container or image → docker debug mongodb
    Learn more at https://docs.docker.com/go/debug-cli/
In [74]:
import pymongo


myclient = pymongo.MongoClient("mongodb://localhost:27017/")

print(myclient.list_database_names())
mydb = myclient["test_db"]
['admin', 'config', 'local']

Generate Random Files¶

In [75]:
# create random json data
import random
import json
from faker import Faker

fake = Faker()

def generate_student():
    return {
        "name": fake.name(),
        "age": random.randint(18, 25),
        "email": fake.email(),
        "student_id": fake.unique.uuid4(),
        "grade": random.choice(["1", "2", "3", "4", "5"]),
        "major": random.choice(["Computer Science", "Mathematics", "Biology", "History", "Economics"]),
        "enrolled_courses": random.sample(
            ["Math 101", "CS 102", "History 201", "Biology 110", "Physics 220", "Literature 130"], 
            k=random.randint(1, 4)
        )
    }

def generate_students(n=100):
    return [generate_student() for _ in range(n)]


student_data = generate_students(200)
for i, student in enumerate(student_data):
    with open(f"mongo_data/student_{i}.json", "w") as f:
        json.dump(student, f, indent=2)
In [76]:
# insert data
mycol = mydb["test_collection"]

# get paths to json files
import os

json_files = [f"mongo_data/student_{i}.json" for i in range(200)]
# insert json data into mongodb
for json_file in json_files:
    with open(json_file, "r") as f:
        data = json.load(f)
        mycol.insert_one(data)
# check if data is inserted
print(f"There are {mycol.count_documents({})} documents in the collection.")
There are 200 documents in the collection.

Update¶

In [77]:
# Print the document before the update
before_update = mycol.find_one({"student_id": student_data[0]["student_id"]})
print("Before update:", before_update['major'])

# Perform the update
mycol.update_one({"student_id": student_data[0]["student_id"]}, {"$set": {"major": "Psychology"}})

# Print the document after the update
after_update = mycol.find_one({"student_id": student_data[0]["student_id"]})
print("After update:", after_update['major'])
Before update: Mathematics
After update: Psychology

Partial Update¶

In [78]:
# Replace first name of first student
before_update = mycol.find_one({"student_id": student_data[0]["student_id"]})
print("Before update:", before_update['name'])

# Split the name into first and last names
full_name = before_update["name"].split(" ", 1)  # Split into first name and the rest
first_name = "Alicia"  # New first name
last_name = full_name[1] if len(full_name) > 1 else ""  # Keep the last name if it exists

# Update the name in the database
mycol.update_one(
    {"student_id": student_data[0]["student_id"]},
    {"$set": {"name": f"{first_name} {last_name}".strip()}}
)

# Print the document after the update
after_update = mycol.find_one({"student_id": student_data[0]["student_id"]})
print("After update:", after_update['name'])
Before update: Nicholas Walker
After update: Alicia Walker

Query¶

In [79]:
# Get Students with first name starting with "Alicia"
query = {"name": {"$regex": "^Alicia", "$options": "i"}}
results = mycol.find(query)

# Convert the results to a DataFrame
import pandas as pd
pd.DataFrame(list(results))
Out[79]:
_id name age email student_id grade major enrolled_courses
0 681c7ceb6d25e4abffcb9e98 Alicia Walker 22 gonzalezpeter@example.org 204e1192-21de-4932-a45f-e7ce850bec3b 4 Psychology [Physics 220, Math 101, Biology 110]
In [80]:
# Get Students in Grade 1
query = {"grade": "1"}
results = mycol.find(query)
pd.DataFrame(list(results)).head(10)
Out[80]:
_id name age email student_id grade major enrolled_courses
0 681c7ceb6d25e4abffcb9e9b Nathan Levine 23 pbaker@example.net 5046ada5-9deb-4aab-8ad6-d303dbb41a37 1 Computer Science [History 201]
1 681c7ceb6d25e4abffcb9e9d Robert King DDS 24 qpotter@example.org e21aab68-462d-48c2-b619-828599685ff6 1 History [CS 102, History 201, Literature 130, Physics ...
2 681c7ceb6d25e4abffcb9ea1 Cynthia Harper 19 julie06@example.net 44002913-59bd-4949-8dc8-682ff39d0662 1 Economics [Biology 110, History 201]
3 681c7ceb6d25e4abffcb9ea3 Diane Myers 19 davidjones@example.net 9541766f-8a48-469c-a961-5210ba083831 1 Biology [History 201, Biology 110, Literature 130]
4 681c7ceb6d25e4abffcb9ea4 Ashley Mcbride 18 coxadam@example.org e036b11a-65f2-4453-afd9-fd244d9d49a2 1 Economics [Math 101, Biology 110, CS 102, Physics 220]
5 681c7ceb6d25e4abffcb9ea6 David Rodriguez 25 sabrina06@example.net 6e2cc7fa-dbc0-42cb-9033-44bf4df89767 1 Computer Science [Physics 220, CS 102]
6 681c7ceb6d25e4abffcb9ea9 Andrew Flores 19 anthony86@example.com f8b1ec35-6948-4b2e-a5d6-8df2a5968d52 1 Computer Science [Physics 220, Biology 110, Literature 130]
7 681c7ceb6d25e4abffcb9eae Teresa Kelly 21 sarah92@example.org 6ae40a84-35fe-47d1-a0b9-1aed87eede1f 1 Mathematics [Biology 110, Literature 130, Math 101]
8 681c7ceb6d25e4abffcb9eb3 Megan Bennett 19 jasmine07@example.net 3583a7c8-e25c-40df-b084-fc6340582458 1 Economics [Biology 110, Physics 220, History 201]
9 681c7ceb6d25e4abffcb9eb9 Carolyn Morris 20 charlesfisher@example.net 51639d7e-db7d-4002-a775-6554b9cbceff 1 Biology [Biology 110, Physics 220, History 201]

Delete¶

In [81]:
# delete documents from alicia

query = {"name": {"$regex": "^Alicia", "$options": "i"}}
mycol.delete_many(query)

results = mycol.find(query)
assert len(list(results)) == 0, "Documents were not deleted successfully"

# delete all documents
mycol.delete_many({})
# check if data is deleted
print(f"There are {mycol.count_documents({})} documents in the collection.")
There are 0 documents in the collection.

Remove container¶

In [82]:
!docker stop mongodb
!docker rm mongodb
mongodb
mongodb