Insert a Pandas Dataframe into mongodb using PyMongo
Here you have the very quickest way. Using the insert_many
method from pymongo 3 and 'records' parameter of to_dict
method.
db.collection.insert_many(df.to_dict('records'))
I doubt there is a both quickest and simple method. If you don't worry about data conversion, you can do
>>> import json>>> df = pd.DataFrame.from_dict({'A': {1: datetime.datetime.now()}})>>> df A1 2013-11-23 21:14:34.118531>>> records = json.loads(df.T.to_json()).values()>>> db.myCollection.insert(records)
But in case you try to load data back, you'll get:
>>> df = read_mongo(db, 'myCollection')>>> df A0 1385241274118531000>>> df.dtypesA int64dtype: object
so you'll have to convert 'A' columnt back to datetime
s, as well as all not int
, float
or str
fields in your DataFrame
. For this example:
>>> df['A'] = pd.to_datetime(df['A'])>>> df A0 2013-11-23 21:14:34.118531