【问题标题】:Export pymongo collection to a JSON file将 pymongo 集合导出到 JSON 文件
【发布时间】:2022-02-22 20:29:24
【问题描述】:

如何将 pymongo 集合导出到 JSON 文件,我有一个巨大的集合,其中包含大约 1 GB 的数据,我需要一种有效的方法来导出数据并从中创建 JSON 文件。 我正在使用以下代码,如堆栈溢出答案之一所述。

def getJSONFromDB():
    db = GetMongo_client()
    collection = db['collection_name']
    cursor = collection.find({})
    file = open("collection.json", "w")
    file.write('[')
    for document in cursor:
      file.write(json.dumps(document))
      file.write(',')
    file.write(']') 

但它给了我以下错误: TypeError: ObjectId 类型的对象不是 JSON 可序列化的

【问题讨论】:

标签: python mongodb pymongo


【解决方案1】:

您指出的 pymongo 文档已过时。如果您使用的是 1.7 版,我建议您更新。使用更新的版本,您可以这样做:

从 bson.json_util 导入转储

转储(l) https://pymongo.readthedocs.io/en/stable/api/bson/json_util.html

侧面回答:u'name'、u'date'、u'_id' 等是数据库中文档的字段名称。

【讨论】:

    猜你喜欢
    • 2018-08-15
    • 2020-01-02
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    相关资源
    最近更新 更多