I have been able to insert data from a csv into a MongoDB by using using PyMongo in the below code.
from pymongo import MongoClient
import urllib
import pandas as pd
import time
import json
client = MongoClient()
db = client.MainDB
col = db.Test
def csv_to_json(filename, header=0):
data = pd.read_csv(filename, header=header, error_bad_lines=False, warn_bad_lines=False, sep='|', low_memory=True)
return json.loads(data.to_dict(orient='records'))
try:
col.insert_many(csv_to_json('main.csv'))
except Exception as e:
print(e)
Now, I will have to be updating this collection daily with the same csv but with different values for certain fields. This is what i came up with and it didnt work. How do i go about this, please.
from pymongo import MongoClient
import urllib
import pandas as pd
import json
import time
starttime = time.time()
client = MongoClient()
db = client.MainDB
col = db.Test
def csv_to_json(filename, header=0):
data = pd.read_csv(filename, header=header, error_bad_lines=False, warn_bad_lines=False, sep='|', low_memory=True)
return data.to_dict(orient='dict')
try:
col.update({}, csv_to_json('main.csv'),upsert=True)
except Exception as e:
print(e)