PyMongo/Mongoengine equivalent of mongodump

喜欢而已 提交于 2020-01-23 05:51:24

问题


Is there an equivalent function in PyMongo or mongoengine to MongoDB's mongodump? I can't seem to find anything in the docs.

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.

Thanks a lot :-).


回答1:


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))


来源:https://stackoverflow.com/questions/24610484/pymongo-mongoengine-equivalent-of-mongodump

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!