In [7]:
Copied!
from pymongo import MongoClient, ReadPreference
from pymongo.read_concern import ReadConcern
from pymongo.write_concern import WriteConcern
from pymongo.errors import ConnectionFailure
from bson import ObjectId
from datetime import datetime, timedelta, timezone
import pprint
USE_ATLAS = False
ATLAS_URI = "mongodb+srv://<username>:<password>@<cluster>.mongodb.net/?retryWrites=true&w=majority"
DOCKER_URI = "mongodb://127.0.0.1:27017/?directConnection=true"
uri = ATLAS_URI if USE_ATLAS else DOCKER_URI
client = MongoClient(uri, serverSelectionTimeoutMS=5000)
try:
client.admin.command("ping")
print("✅ Connected to", "Atlas" if USE_ATLAS else "Docker MongoDB")
except ConnectionFailure as e:
print("❌ Connection failed:", e)
db = client["mongo_labs"]
pp = pprint.PrettyPrinter(indent=2)
from pymongo import MongoClient, ReadPreference
from pymongo.read_concern import ReadConcern
from pymongo.write_concern import WriteConcern
from pymongo.errors import ConnectionFailure
from bson import ObjectId
from datetime import datetime, timedelta, timezone
import pprint
USE_ATLAS = False
ATLAS_URI = "mongodb+srv://<username>:<password>@<cluster>.mongodb.net/?retryWrites=true&w=majority"
DOCKER_URI = "mongodb://127.0.0.1:27017/?directConnection=true"
uri = ATLAS_URI if USE_ATLAS else DOCKER_URI
client = MongoClient(uri, serverSelectionTimeoutMS=5000)
try:
client.admin.command("ping")
print("✅ Connected to", "Atlas" if USE_ATLAS else "Docker MongoDB")
except ConnectionFailure as e:
print("❌ Connection failed:", e)
db = client["mongo_labs"]
pp = pprint.PrettyPrinter(indent=2)
✅ Connected to Docker MongoDB
Embedding (co-accessed data)¶
In [8]:
Copied!
db.users_embedded.drop()
user_id = db.users_embedded.insert_one({"name":"Alice","email":"alice@example.com","address":{"city":"NYC","state":"NY"},"tags":["premium"]}).inserted_id
user = db.users_embedded.find_one({"email":"alice@example.com"})
print("City:", user["address"]["city"])
db.users_embedded.drop()
user_id = db.users_embedded.insert_one({"name":"Alice","email":"alice@example.com","address":{"city":"NYC","state":"NY"},"tags":["premium"]}).inserted_id
user = db.users_embedded.find_one({"email":"alice@example.com"})
print("City:", user["address"]["city"])
City: NYC
In [9]:
Copied!
# Query on embedded field
for u in db.users_embedded.find({"address.city":"NYC"},{"_id":0,"name":1}):
print(u["name"])
# Query on embedded field
for u in db.users_embedded.find({"address.city":"NYC"},{"_id":0,"name":1}):
print(u["name"])
Alice
Referencing (unbounded growth)¶
In [10]:
Copied!
db.users_ref.drop()
db.orders_ref.drop()
bob_id = db.users_ref.insert_one({"name":"Bob","email":"bob@example.com"}).inserted_id
db.orders_ref.insert_many([{"userId":bob_id,"status":"delivered","total":349.99},{"userId":bob_id,"status":"pending","total":49.99}])
user = db.users_ref.find_one({"_id":bob_id})
orders = list(db.orders_ref.find({"userId":bob_id}))
print(f"{user['name']}: {len(orders)} orders")
db.users_ref.drop()
db.orders_ref.drop()
bob_id = db.users_ref.insert_one({"name":"Bob","email":"bob@example.com"}).inserted_id
db.orders_ref.insert_many([{"userId":bob_id,"status":"delivered","total":349.99},{"userId":bob_id,"status":"pending","total":49.99}])
user = db.users_ref.find_one({"_id":bob_id})
orders = list(db.orders_ref.find({"userId":bob_id}))
print(f"{user['name']}: {len(orders)} orders")
Bob: 2 orders
$lookup (runtime join)¶
In [11]:
Copied!
result = list(db.users_ref.aggregate([{"$match":{"_id":bob_id}},{"$lookup":{"from":"orders_ref","localField":"_id","foreignField":"userId","as":"orders"}}]))
print("Joined orders:", len(result[0]["orders"]))
result = list(db.users_ref.aggregate([{"$match":{"_id":bob_id}},{"$lookup":{"from":"orders_ref","localField":"_id","foreignField":"userId","as":"orders"}}]))
print("Joined orders:", len(result[0]["orders"]))
Joined orders: 2
Many-to-Many (edge collection)¶
In [12]:
Copied!
db.courses.drop()
db.students.drop()
db.enrollments.drop()
db.courses.insert_many([{"_id":ObjectId("c00000000000000000000001"),"title":"MongoDB"},{"_id":ObjectId("c00000000000000000000002"),"title":"Aggregation"}])
db.students.insert_many([{"_id":ObjectId("s00000000000000000000001"),"name":"Dave"},{"_id":ObjectId("s00000000000000000000002"),"name":"Eve"}])
db.enrollments.insert_many([{"studentId":ObjectId("s00000000000000000000001"),"courseId":ObjectId("c00000000000000000000001")},{"studentId":ObjectId("s00000000000000000000001"),"courseId":ObjectId("c00000000000000000000002")}])
db.enrollments.create_index("studentId")
db.enrollments.create_index("courseId")
courses = list(db.enrollments.find({"studentId":ObjectId("s00000000000000000000001")}))
print("Dave enrolled in:", len(courses), "courses")
db.courses.drop()
db.students.drop()
db.enrollments.drop()
db.courses.insert_many([{"_id":ObjectId("c00000000000000000000001"),"title":"MongoDB"},{"_id":ObjectId("c00000000000000000000002"),"title":"Aggregation"}])
db.students.insert_many([{"_id":ObjectId("s00000000000000000000001"),"name":"Dave"},{"_id":ObjectId("s00000000000000000000002"),"name":"Eve"}])
db.enrollments.insert_many([{"studentId":ObjectId("s00000000000000000000001"),"courseId":ObjectId("c00000000000000000000001")},{"studentId":ObjectId("s00000000000000000000001"),"courseId":ObjectId("c00000000000000000000002")}])
db.enrollments.create_index("studentId")
db.enrollments.create_index("courseId")
courses = list(db.enrollments.find({"studentId":ObjectId("s00000000000000000000001")}))
print("Dave enrolled in:", len(courses), "courses")
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) File ~/Programming/MongoDBLeaning/venv/lib/python3.9/site-packages/bson/objectid.py:112, in ObjectId.__init__(self, oid) 111 try: --> 112 self.__id = bytes.fromhex(oid) 113 except (TypeError, ValueError): ValueError: non-hexadecimal number found in fromhex() arg at position 0 During handling of the above exception, another exception occurred: InvalidId Traceback (most recent call last) Cell In[12], line 5 3 db.enrollments.drop() 4 db.courses.insert_many([{"_id":ObjectId("c00000000000000000000001"),"title":"MongoDB"},{"_id":ObjectId("c00000000000000000000002"),"title":"Aggregation"}]) ----> 5 db.students.insert_many([{"_id":ObjectId("s00000000000000000000001"),"name":"Dave"},{"_id":ObjectId("s00000000000000000000002"),"name":"Eve"}]) 6 db.enrollments.insert_many([{"studentId":ObjectId("s00000000000000000000001"),"courseId":ObjectId("c00000000000000000000001")},{"studentId":ObjectId("s00000000000000000000001"),"courseId":ObjectId("c00000000000000000000002")}]) 7 db.enrollments.create_index("studentId") File ~/Programming/MongoDBLeaning/venv/lib/python3.9/site-packages/bson/objectid.py:114, in ObjectId.__init__(self, oid) 112 self.__id = bytes.fromhex(oid) 113 except (TypeError, ValueError): --> 114 _raise_invalid_id(oid) 115 else: 116 _raise_invalid_id(oid) File ~/Programming/MongoDBLeaning/venv/lib/python3.9/site-packages/bson/objectid.py:37, in _raise_invalid_id(oid) 36 def _raise_invalid_id(oid: str) -> NoReturn: ---> 37 raise InvalidId( 38 "%r is not a valid ObjectId, it must be a 12-byte input" 39 " or a 24-character hex string" % oid 40 ) InvalidId: 's00000000000000000000001' is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string