【发布时间】:2017-05-27 06:52:37
【问题描述】:
我想将 Mongo 数据库的数据转储到一个 csv/excel 文件中。 我的数据库有几个具有相同字段和嵌入字段的文档。我希望每个嵌入字段是我的 csv 文件的一列,每个文档是一行。 这是目标:
a_cursor = a_collection.find(filter, projection) # pymongo.collection.find() method
a_csv_file = print_cursor_to_csv(a_cursor,projection) # the method I would like to create
- 使用 find() 的 filter 参数,我将能够过滤 mongo 文档。
- 使用 find() 的投影参数,我将选择要放入 csv 列的字段。
- 在 print_cursor_to_csv() 中再次使用了投影参数,这一次只是为了给出 csv 文件的字段/列的顺序。实际上,projection 是一个字段列表,第一个字段将是第一个 csv 列。
这是我写的方法:
def _print_cursor_in_csv(cursor, fields_to_show_order):
"""
:param cursor: pymongo.Cursor. The list of documents to print into csv.
:param fields_to_show_order: List of String. Permits to know the order of columns chosen by the user.
Example : BaseStation_ID as first columns, then frequency of utilisation etc..
"""
flattened_cursor = []
for a_document in cursor:
flattened_cursor.append(_flatten_the_dict(a_document))
string_csv = _get_string_csv_from_list_of_dicts(flattened_cursor, fields_to_show_order)
_write_a_file_from_a_string("testCSV"+".csv", string_csv) # PRINT CSV OF A DOC
我的方法有效,但很大,我想更多地依赖 python 库,例如 pandas、openpyxl 或 csv。也许他们中的一个人可以在扁平化每个字典后从字典列表中编写一个 csv 文件。
感谢您的帮助,
马蒂亚斯
【问题讨论】:
标签: python mongodb csv pandas pymongo