如何使用pymongo将集合转储到json文件 [英] How to dump a collection to json file using pymongo

查看:617
本文介绍了如何使用pymongo将集合转储到json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to dump a collection to .json file but after looking in pymongo tutorial I can not find any thing that relates to it.

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

推荐答案

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

Just get all documents and save them to file e.g.:

import json
from pymongo import MongoClient

if __name__ == '__main__':
    client = MongoClient()
    db = client.db_name
    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(']')

这篇关于如何使用pymongo将集合转储到json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆