如何使用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.
答
只需获取所有文档并将其保存到文件中,例如:
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(']')