Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyMongo/Mongoengine equivalent of mongodump

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

like image 233
Gx1sptDTDa Avatar asked Jul 07 '14 12:07

Gx1sptDTDa


People also ask

Should I use PyMongo or MongoEngine?

Both PyMongo and MongoEngine can be used to access data from a MongoDB database. However, they work in very different ways and offer different features. PyMongo is the MongoDB recommended library. It makes it easy to use MongoDB documents and maps directly to the familiar MongoDB Query Language.

Does MongoEngine use PyMongo?

Author of MongoEngine here - MongoEngine is built upon pymongo so of course you can drop into pymongo - or use raw pymongo in your code!

What is Mongodump and Mongorestore?

Database backup is a copy of a database that already exists. In MongoDB, mongodump tool is used to take the data backup. And mongorestore tool is used to restore the backup data.


1 Answers

The accepted answer is not working anymore. Here is a revised code:

from os.path import join
import pymongo
from bson.json_util import dumps

def backup_db(backup_db_dir):
    client = pymongo.MongoClient(host=..., port=..., username=..., password=...)
    database = client[<db_name>]
    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).encode())


backup_db('.')
like image 159
CIsForCookies Avatar answered Oct 03 '22 10:10

CIsForCookies