Python script to take mongodb backup

@Author: Aseem Jain

import os
import pymongo

# configure credentials / db name
db_user = os.environ["MONGO_ATLAS_USER"]
db_pass = os.environ["MONGO_ATLAS_PASSWORD"]
db_name = "sample_mflix"

connection_string = f"mongodb+srv://{db_user}:{db_pass}{db_name}?retryWrites=true&w=majority"

client = pymongo.MongoClient(connection_string)
db = client[db_name]

# create database back directory with db_name
os.makedirs(db_name, exist_ok=True)

# list all tables in database
tables = db.list_collection_names()

# dump all tables in db
for table in tables:
print("exporting data for table", table )
data = list(db[table].find())
# write data in json file
with open(f"{}/{table}.json","w") as writer:


How to export data from mongoDB

# Make sure that we have mongoD process running and file below command from bash and not from Mongo shell to export data. This will export data for one collection in Db, to export entire DB use mongo dump

MQ428GG8WL:week2 asee2278$ mongoexport –db students –collection grades –out gradesOut.json

  • 2016-01-14T14:21:18.813-0600 connected to: localhost
  • 2016-01-14T14:21:18.831-0600 exported 800 record

Sample exported record would look like :