面试题答案
一键面试- 具体步骤:
- 连接到MongoDB数据库。
- 选择要备份的数据库和集合。
- 读取集合中的所有文档。
- 将文档写入到本地的
backup.json
文件中。
- 核心代码示例:
import pymongo
import json
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['test_db']
collection = db['test_collection']
data = list(collection.find())
with open('backup.json', 'w', encoding='utf - 8') as f:
json.dump(data, f, ensure_ascii=False, default=str)