-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmongoSaver.py
More file actions
37 lines (28 loc) · 1.07 KB
/
mongoSaver.py
File metadata and controls
37 lines (28 loc) · 1.07 KB
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
from pymongo import MongoClient
import csv
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
import os
from dotenv import load_dotenv
DB_NAME = 'CarletonPathwaysDB'
class MongoSaver:
def __init__(self):
load_dotenv()
#Connects to the Mongo client
self.client = MongoClient(os.getenv('URI'), server_api=ServerApi('1'))
def save_csv_to_mongo(self, collection_name, csv_path):
#Specifies what Database and collection to add to
self.client.admin.command('ping')
database = self.client[DB_NAME]
collection = database[collection_name]
try:
#Opens CSV and adds to MongoDB
with open(csv_path, 'r',encoding='utf-8') as file:
reader = csv.DictReader(file)
for row in reader:
collection.insert_one(row)
print("Sucessfully connected and inserted data")
except Exception as e:
print(e)
def close_mongo_connection(self):
self.client.close()