首页 > 解决方案 > 我可以从 mongo shell 中恢复 mongo db 吗?

问题描述

无论如何,当您使用 shell 时,转储和恢复 mongo db 似乎相当简单:您只需使用命令mongorestoremongodump. 但如果我没记错的话,这些命令要求您离开活动的mongo shell

此外,在使用 Python 或 Prolog 编写时,我有不同的方式与 mongo 进行通信。我可以使用 PyMonogo 或者在我的情况下,我通过RosProlog进行通信。两者都可以执行 mongo shell 命令,但我想不出一种方法来执行类似于mongorestoreand的东西mongodump

当然,我可以os.system()在 Python(或process_create/3prolog)中使用来执行 shell 命令,但它看起来很丑陋,我想避免它。我也可以自己编写一个 .bson-parser ,但这真的有必要吗?mongo shell中真的没有等价物吗?

标签: pythonmongodbprologmongodumpmongorestore

解决方案


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 的情况下错过一些边缘情况。


推荐阅读