pymongo mongodump code example

Example 1: mongodump

mongodump -h <127.0.0.1>:<27017> -d <db> -u <user> -p <pw> -o ./
mongorestore ./

Example 2: python mongodump

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('.')