Skip to content

Instantly share code, notes, and snippets.

@Lh4cKg
Created January 22, 2020 07:50
Show Gist options
  • Save Lh4cKg/939ce683e2876b314a205b3f8c6e8e9d to your computer and use it in GitHub Desktop.
Save Lh4cKg/939ce683e2876b314a205b3f8c6e8e9d to your computer and use it in GitHub Desktop.
MongoDB Dump And Restore Database With Python PyMongo Driver
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()))
@DrSnowbird
Copy link

Thanks! It's very helpful!

@hougomartim
Copy link

thank you very much. This is great.

@Odzen
Copy link

Odzen commented Jan 17, 2025

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