- import json
- import os
- import pymongo
- # 连接数据库
- client = pymongo.MongoClient('localhost', 27017)
- # 数据库保存文件夹
- db_path = './data_back'
- # 获取所有mongoDB的数据库名称
- db_list = client.list_database_names()
- # 去除数据库名称列表中的system数据库
- admin_list = ['admin', 'local', 'config']
- db_list = [db for db in db_list if db not in admin_list] # 去除数据库名称中无关的数据库
- # 循环遍历数据库名称保存数据到json中
- for db_name in db_list:
- # 连接数据库
- db = client[db_name]
- # 获取数据库中所有的集合名称
- collection_list = db.list_collection_names()
- # 去除集合名称列表中的system数据库
- collection_list = [collection for collection in collection_list if collection not in admin_list]
- # 循环遍历集合名称保存数据到json中
- for collection_name in collection_list:
- # 连接集合
- collection = db[collection_name]
- # 获取集合中所有的文档
- # with 上下文进行管理,设置no_cursor_timeout=True参数,让游标不会超时,防止程序阻塞
- with collection.find({}, {"_id": 0}, no_cursor_timeout=True) as cursor:
- # 循环遍历文档保存数据到json中
- for row in cursor:
- # 创建文件夹
- if not os.path.exists(db_path):
- os.makedirs(db_path)
- # 创建文件
- with open(os.path.join(db_path, db_name + '_' + collection_name + '.json'), 'a') as f:
- # 将文档写入文件
- f.write(json.dumps(row, ensure_ascii=False) + '\n')
复制代码
|