首页 > 解决方案 > 使用 PyMongo 将 JSON 分块保存

问题描述

我在 MongoDB 中有一个相当大的集合,我需要使用 PyMongo 将整个内容导出到 JSON。现在我只是在做:

import json

results = db.collection_name.find()

with open('collection-data.json', 'w') as f:
    json.dump(list(results), f)

这最终导致内核崩溃,因为它耗尽了我所有的内存。有没有办法将集合保存在块中,这样我就不会一次检索所有数据?

标签: pythonmongodbpymongo

解决方案


在你的 shell 中试试这个:

mongoexport --db <database-name> --collection <collection-name> --out output.json

推荐阅读