python - 如何使用 pymongo 将集合转储到 json 文件

标签 python json mongodb pymongo-3.x

我试图将一个集合转储到 .json 文件,但在查看 pymongo 教程后我找不到任何与之相关的东西。

教程链接:https://api.mongodb.com/python/current/tutorial.html

最佳答案

只需获取所有文档并将它们保存到文件中,例如:

from bson.json_util import dumps
from pymongo import MongoClient

if __name__ == '__main__':
    client = MongoClient()
    db = client.db_name
    collection = db.collection_name
    cursor = collection.find({})
    with open('collection.json', 'w') as file:
        file.write('[')
        for document in cursor:
            file.write(dumps(document))
            file.write(',')
        file.write(']')

关于python - 如何使用 pymongo 将集合转储到 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49153020/

相关文章:

java - Android 应用的 JSON 编码数据

javascript - Backbone如何获取数组中的特定对象

node.js - Mongo DB 文档只返回 "_id" "$oid"

python flask-restful 无法在资源类中获取应用程序访问权限

python - 使用 Python 和正则表达式查找字符串中的所有中文文本

javascript - 如何在 Javascript 中转换 JSON 字节

javascript - 忽略子文档 MongoDB 中的某些结果

mongodb - 在 mongodb 投影中组合 $elemMatch 和 $

python - 如何向另一台服务器发送请求并在 Pyramid View 中响应结果?

python - 使用在线数据增强来比较 CNN 模型是否公平