"""
@Author: Aseem Jain
@profile: https://www.linkedin.com/in/premaseem/
"""
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}@sharedcluster.lv3wx.mongodb.net/{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"{db.name}/{table}.json","w") as writer:
writer.write(str(data))
exit(0)
Tag Archives: mongoDB export
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 :
{"_id":{"$oid":"50906d7fa3c412bb040eb583"},"score":92.6244233936537,"student_id":3,"type":"exam"}