MST

星途 面试题库

面试题:Python中如何使用pymongo库备份MongoDB数据库的单个集合?

请描述使用Python的pymongo库备份MongoDB数据库中某个特定集合的具体步骤,并给出核心代码示例。假设已经安装好pymongo库,且连接MongoDB数据库的代码为`client = pymongo.MongoClient('mongodb://localhost:27017/')`,数据库名称为`test_db`,集合名称为`test_collection`,需要将数据备份到本地文件`backup.json`。
22.5万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
  1. 具体步骤
    • 连接到MongoDB数据库。
    • 选择要备份的数据库和集合。
    • 读取集合中的所有文档。
    • 将文档写入到本地的backup.json文件中。
  2. 核心代码示例
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)