PyMongo/Mongoengine等价于mongodump [英] PyMongo/Mongoengine equivalent of mongodump
问题描述
在PyMongo
或mongoengine
中是否有与MongoDB的mongodump
等效的功能?我似乎在文档中找不到任何内容.
Is there an equivalent function in PyMongo
or mongoengine
to MongoDB's mongodump
? I can't seem to find anything in the docs.
用例:我需要定期备份远程mongo数据库.本地计算机是未安装mongo的生产服务器,并且我没有管理员权限,因此无法使用subprocess
调用mongodump
.我可以在virtualenv上本地安装mongo客户端,但是我更喜欢API调用.
Use case: I need to periodically backup a remote mongo database. The local machine is a production server that does not have mongo installed, and I do not have admin rights, so I can't use subprocess
to call mongodump
. I could install the mongo client locally on a virtualenv, but I'd prefer an API call.
非常感谢:-).
推荐答案
对于我相对较小的小型数据库,我最终使用了以下解决方案.它并不真正适用于大型数据库或复杂数据库,但足以满足我的情况.它将所有文档作为json转储到备份目录.它笨拙,但是除了pymongo之外,它不依赖其他任何东西.
For my relatively small small database, I eventually used the following solution. It's not really suitable for big or complex databases, but it suffices for my case. It dumps all documents as a json to the backup directory. It's clunky, but it does not rely on other stuff than pymongo.
from os.path import join
import pymongo
from bson.json_utils import dumps
def backup_db(backup_db_dir):
client = pymongo.MongoClient(host=<host>, port=<port>)
database = client[<db_name>]
authenticated = database.authenticate(<uname>,<pwd>)
assert authenticated, "Could not authenticate to database!"
collections = database.collection_names()
for i, collection_name in enumerate(collections):
col = getattr(database,collections[i])
collection = col.find()
jsonpath = collection_name + ".json"
jsonpath = join(backup_db_dir, jsonpath)
with open(jsonpath, 'wb') as jsonfile:
jsonfile.write(dumps(collection))
这篇关于PyMongo/Mongoengine等价于mongodump的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!