-
-
Save royz/8907fcceef4e63cbd22c561e435da000 to your computer and use it in GitHub Desktop.
MongoDB Dump And Restore Database With Python PyMongo Driver
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import bson | |
from pymongo import MongoClient | |
def dump(collections, conn, db_name, path): | |
""" | |
MongoDB Dump | |
:param collections: Database collections name | |
:param conn: MongoDB client connection | |
:param db_name: Database name | |
:param path: | |
:return: | |
>>> DB_BACKUP_DIR = '/path/backups/' | |
>>> conn = MongoClient("mongodb://admin:[email protected]:27017", authSource="admin") | |
>>> db_name = 'my_db' | |
>>> collections = ['collection_name', 'collection_name1', 'collection_name2'] | |
>>> dump(collections, conn, db_name, DB_BACKUP_DIR) | |
""" | |
db = conn[db_name] | |
for coll in collections: | |
with open(os.path.join(path, f'{coll}.bson'), 'wb+') as f: | |
for doc in db[coll].find(): | |
f.write(bson.BSON.encode(doc)) | |
def restore(path, conn, db_name): | |
""" | |
MongoDB Restore | |
:param path: Database dumped path | |
:param conn: MongoDB client connection | |
:param db_name: Database name | |
:return: | |
>>> DB_BACKUP_DIR = '/path/backups/' | |
>>> conn = MongoClient("mongodb://admin:[email protected]:27017", authSource="admin") | |
>>> db_name = 'my_db' | |
>>> restore(DB_BACKUP_DIR, conn, db_name) | |
""" | |
db = conn[db_name] | |
for coll in os.listdir(path): | |
if coll.endswith('.bson'): | |
with open(os.path.join(path, coll), 'rb+') as f: | |
db[coll.split('.')[0]].insert_many(bson.decode_all(f.read())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment