Pandas - insert a dataframe to MongoDB
You were very close, we can re-use your code.
Note, we still use pymongo.MongoClient
and pandas.DataFrame.to_dict
, with one param added in the latter.to_dict(orient='records')
we would then have
from pymongo import MongoClientimport pandas as pdclient = MongoClient() # Remember your uri stringcol = client['test']['test']df = pd.DataFrame({'name': ['Braund','Cummings','Heikkinen','Allen'], 'age': [22,38,26,35], 'fare': [7.25, 71.83, 0 , 8.05], 'survived?': [False, True, True, False]})data = df.to_dict(orient='records') # Here's our added param..col.insert_many(data)
In short, by specifying orient='records'
the output is a list of dicts, the same format accepted by insert_many
. Also, as a bonus - to_dict
does better with datetime-type columns as compared to to_json
!