Created
January 22, 2020 07:50
-
-
Save Lh4cKg/939ce683e2876b314a205b3f8c6e8e9d to your computer and use it in GitHub Desktop.
MongoDB Dump And Restore Database With Python PyMongo Driver
This file contains 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())) |
thank you very much. This is great.
import os
isn't this line missing?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! It's very helpful!