לדלג לתוכן

1.4 מבני נתונים א רלציונים פתרון

פתרון תרגול – הרחבת פרויקט TRIP עם MongoDB (Embedded Documents)


1. מבנה המסמכים במסד MongoDB

ב־MongoDB נשתמש ב־Collection אחד בשם trips, וכל טיול ישמור בתוכו את כל המידע שקשור אליו.

מבנה מסמך Trip

{
  "_id": ObjectId,
  "name": "טיול ללונדון",
  "people": 3,
  "hotels": [
    {
      "hotel_id": ObjectId,
      "name": "Hilton",
      "stars": 5
    }
  ],
  "flights": [
    {
      "flight_id": ObjectId,
      "airline": "EL AL",
      "from_city": "TLV",
      "to_city": "LHR"
    }
  ]
}

חיבור ל־MongoDB בפייתון

from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017")
db = client.trip_db
trips_collection = db.trips

קונטרולר

def get_trip(trip_id: str):
    return trips_collection.find_one({"_id": ObjectId(trip_id)})

def add_hotel_to_trip(trip_id: str, hotel: dict):
    trips_collection.update_one(
        {"_id": ObjectId(trip_id)},
        {"$push": {"hotels": hotel}}
    )

def remove_hotel_from_trip(trip_id: str, hotel_name: str):
    trips_collection.update_one(
        {"_id": ObjectId(trip_id)},
        {"$pull": {"hotels": {"name": hotel_name}}}
    )

ראוטים

from fastapi import APIRouter
from bson import ObjectId

router = APIRouter()

@router.get("/trips/{trip_id}")
def get_trip_route(trip_id: str):
    return get_trip(trip_id)

@router.post("/trips/{trip_id}/hotels")
def add_hotel(trip_id: str, hotel: dict):
    add_hotel_to_trip(trip_id, hotel)
    return {"status": "hotel added"}

@router.delete("/trips/{trip_id}/hotels/{hotel_name}")
def delete_hotel(trip_id: str, hotel_name: str):
    remove_hotel_from_trip(trip_id, hotel_name)
    return {"status": "hotel removed"}