Forked from jxub/pandas_labeled_csv_import_to_mongo.py
Last active
February 21, 2024 20:32
-
-
Save shashwata27/cff6a8c11afa147793b6d964f58d81ba to your computer and use it in GitHub Desktop.
A simple mongoimport for importing csv files with python and pymongo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
from pymongo import MongoClient | |
import json | |
def mongoimport(csv_path, db_name, coll_name, db_url='localhost', db_port=27000) | |
""" Imports a csv file at path csv_name to a mongo colection | |
returns: count of the documants in the new collection | |
""" | |
client = MongoClient(db_url, db_port) | |
db = client[db_name] | |
coll = db[coll_name] | |
data = pd.read_csv(csv_path) | |
payload = json.loads(data.to_json(orient='records')) | |
coll.remove() | |
coll.insert(payload) | |
return coll.count() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment