python - 我可以从 mongo shell 中恢复 mongo db 吗?
问题描述
无论如何,当您使用 shell 时,转储和恢复 mongo db 似乎相当简单:您只需使用命令mongorestore
和mongodump
. 但如果我没记错的话,这些命令要求您离开活动的mongo shell。
此外,在使用 Python 或 Prolog 编写时,我有不同的方式与 mongo 进行通信。我可以使用 PyMonogo 或者在我的情况下,我通过RosProlog进行通信。两者都可以执行 mongo shell 命令,但我想不出一种方法来执行类似于mongorestore
and的东西mongodump
。
当然,我可以os.system()
在 Python(或process_create/3
prolog)中使用来执行 shell 命令,但它看起来很丑陋,我想避免它。我也可以自己编写一个 .bson-parser ,但这真的有必要吗?mongo shell中真的没有等价物吗?
解决方案
mongodump 和 mongorestore 是用 golang https://github.com/mongodb/mongo-tools编写的操作系统级实用程序。您确实需要在 mongo shell 之外运行它们。
推荐的方法是使用标准的 mongodump 和 mongorestore 作为子进程,但那里没有魔法,你可以在 Python 中做同样的事情。
来自https://jira.mongodb.org/browse/PYTHON-664:
from bson import BSON, decode_all
from pymongo import MongoClient
client = MongoClient()
source_collection = client.db.collection
# Dump.
with open('file.bson', 'wb+') as f:
for doc in source_collection.find():
f.write(BSON.encode(doc))
# Restore.
target_collection = client.db.collection2
with open('file.bson', 'rb') as f:
target_collection.insert(decode_all(f.read()))
它不会那么高效,备份将与标准备份不兼容,并且您可能会在不转储 oplog 的情况下错过一些边缘情况。
推荐阅读
- c++ - 在多个共享库中时静态库成员的多次初始化
- time-complexity - 其中有更高阶的增长,cn(log (base 1.5) n) 或 d.(n^(log (base 1.5) 2))
- python - BeautifulSoup:Python:尝试从多行中提取数据
- kentico - UniversalViewerWithCustomQuery Where 子句使用 QueryString 参数
- javascript - 在移动浏览器中未正确触发 Jquery 点击事件
- time - 如何以亚秒级精度计时操作的持续时间?
- python - 按字母顺序查找最长的子串。我的代码有什么问题
- r - 如何遍历列并创建不同的图?
- python - 熊猫丢弃重复忽略 NaN
- python - Jupyter ModuleError pyaudio