Home Developer Programming Language Framework Articles Contact Me

HTML CSS JAVASCRIPT JAVA PYTHON JQUERY REACTJS VUEJS ANGULARJS EMBERJS SASS LESS STYLUS GITHUB GITLAB BIGBUCKET JAVA KOTLIN HADOOP JDBC SERVLETS JAVA BEANS(EJB) JAVA SERVER PAGES(JSP) UNIX LINUX POSTGRESQL MSSQLSERVER SQLITE MONGODB XML FLASK PYTHON MYSQL JAVA C++ JUNIT SELENIUM

How to Get MongoDB Collection Data in Excel or CSV Format Using Python

Prerequisite:- Pymongo

What is PyMongo?

PyMongo is a Python distribution containing tools for working with MongoDB and is the recommended way to work with MongoDB from Python.

In this article, we will learn, how to get MongoDB collection data in Excel or CSV or in different formats.

Libraries Required:- Pymongo

Installation:-

      
pip install pymongo
    

We are assuming that you have already created collection and data is added in MongoDB.

Approach For Conversion:-

Below is the Implementation:-
      
# Import Required Library
import pymongo
import json 
from pandas import json_normalize
from bson.json_util import dumps

# Add MongoDB Server
cluster = pymongo.MongoClient("Enter MongoDB Server Details")

# Enter DataBase Name
mydb = cluster["Database Name"]

# Enter Collection Name
collection= mydb["Collection Name"]

# Fill query or for all data leave empty
document = collection.find({})

# Convert into string
json_string = dumps(document)

# Converting JSON String to JSON Object
json_obj = json.loads(json_string)

# Converting JSON Object to Pandas Dataframe
data1 = json_normalize(json_obj)

# Enter File Name
data1.to_csv("FileName.csv")
    
Adding Data to MongoDB

Output:-



Data Conversion

Output:-