Spaces:
Sleeping
Sleeping
File size: 1,556 Bytes
9e7b45f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | import pandas as pd
from pymongo import MongoClient
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
MONGO_URI = os.environ.get("MONGO_URI")
DB_NAME = os.environ.get("MONGODB_DB", "attendance_db")
def migrate():
if not MONGO_URI:
print("Error: MONGO_URI not found in environment variables")
return
try:
# Connect to MongoDB
client = MongoClient(MONGO_URI)
db = client[DB_NAME]
collection = db["timetable"]
# Read CSV
csv_path = 'timetable.csv'
if not os.path.exists(csv_path):
print(f"Error: {csv_path} not found")
return
print(f"Reading {csv_path}...")
df = pd.read_csv(csv_path)
# Convert to list of dictionaries
records = df.to_dict(orient='records')
if not records:
print("No records found in CSV")
return
# Clear existing collection
print(f"Dropping existing timetable collection in {DB_NAME}...")
collection.drop()
# Insert new records
print(f"Inserting {len(records)} records from CSV to MongoDB...")
collection.insert_many(records)
print("Migration completed successfully!")
# Verify
count = collection.count_documents({})
print(f"Total documents in timetable collection: {count}")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
migrate()
|