如何使用pymongo将集合转储为json文件

7 浏览
0 Comments

如何使用pymongo将集合转储为json文件

我正在尝试将一个集合转储为.json文件,但在查看pymongo教程后,我找不到任何相关内容。\n教程链接:https://api.mongodb.com/python/current/tutorial.html

0
0 Comments

如何使用pymongo将集合转储到JSON文件

在使用pymongo将集合转储为JSON文件时,有一种方法可以避免在关闭方括号之前保存逗号,并且可以使用`with open`语句来节省一些空间。但是,该方法需要事先知道文档的总数,以便在写入文件时进行判断。

下面是一个示例代码:

filter = {"type": "something"}
type_documents = db['cluster'].find(filter)
type_documents_count = db['cluster'].count_documents(filter)
with open("type_documents.json", "w") as file:
    file.write('[')
    # 从1开始迭代,因为type_documents_count也从1开始计数
    for i, document in enumerate(type_documents, 1):
        file.write(json.dumps(document, default=str))
        if i != type_documents_count:
            file.write(',')
    file.write(']')

这段代码的作用是将满足`{"type": "something"}`条件的文档从集合`cluster`中提取出来,并将它们转储为名为`type_documents.json`的JSON文件。在写入文件时,它会逐个文档地进行处理,并在每个文档之间添加逗号,但是对于最后一个文档,不会添加逗号。

然而,有人认为在转储之前添加逗号会更加高效。这样一来,就不需要事先知道文档的总数,只需检查是否为第一个迭代即可。我们可以将`if i != type_documents_count:`替换为`if i != 1:`,并且不再需要`count_documents`方法。

这样修改后的代码如下:

filter = {"type": "something"}
type_documents = db['cluster'].find(filter)
with open("type_documents.json", "w") as file:
    file.write('[')
    for i, document in enumerate(type_documents, 1):
        if i != 1:
            file.write(',')
        file.write(json.dumps(document, default=str))
    file.write(']')

通过这种方式,我们可以更加高效地将集合转储为JSON文件,而无需提前获取文档的总数。

总结起来,使用pymongo将集合转储为JSON文件时,我们可以选择在转储之前添加逗号,以简化代码并提高效率。

0
0 Comments

问题的原因是使用的解决方案生成了一个无效的JSON,导致在右方括号]之前存在一个尾随逗号,。JSON规范不允许尾随逗号。为了构建在已接受的解决方案上,我使用了以下代码:

from bson.json_util import dumps
from pymongo import MongoClient
import json
if __name__ == '__main__':
    client = MongoClient()
    db = client.db_name
    collection = db.collection_name
    cursor = collection.find({})
    with open('collection.json', 'w') as file:
        json.dump(json.loads(dumps(cursor)), file)

这是我认为最好的解决方案。

0
0 Comments

如何使用pymongo将集合转储为json文件?

我已经添加了一个示例,请看一下。

这会产生类似这样的错误:TypeError: Object of type 'ObjectId' is not JSON serializable。

得到了相同的TypeError。您可以通过导入from bson.json_util import dumps并将行file.write(json.dumps(document))替换为file.write(dumps(document))来解决它。了解更多。

实际上,由于在file.write(']')之前的最后一个file.write(',')将导致文件的',]'无效。

0