Convert MongoDB Document to JSON using Python
In this article, you will learn a simple process to convert MongoDB document data to JSON using the Python programming language.
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is more compact, flexible, and easier to use. It is used primarily to transmit data between a server and a web application. JSON is popular among developers for data serialization. Today, it is more popular than XML.
In Python programming, we need the MongoDB connector module to work with MongoDB. In this article, we will use the 'pymongo' module. If you do not have this module installed, you can easily install it using the pip tool.
(env) c:\python37\Scripts\projects>pip install pymongo
For working with MongoDB, use the following command in a terminal window to start the mongodb daemon-
$ mongod
Import the pymongo in Python file to connect to the database. After importing, create an instance of MongoClient and establish a connection to the default host, i.e., localhost and port 27017.
import pymongo
import json
client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client["school"]
mycol = mydb["students"]
Next, loop over the data and store in a dictionary-
mydict = create_dict()
i = 1
for y in mycol.find():
mydict.add(i, ({"name":y['name'],"age":y['age'],"section":y['section']}))
i = i+1
In the above code, first we have instantiated the create_dict class and called the add() method to store the fetched data in a key-value pair. The class is defined as follows.
class create_dict(dict):
# __init__ function
def __init__(self):
self = dict()
# Function to add key:value
def add(self, key, value):
self[key] = value
Import JSON
To convert the MongoDB data into the JSON format, we need to import the json library. This library contains all the necessary methods to work with JSON.
import JSON
The JSON module provides the dumps() method for writing data to files. This method takes a data object to be serialized, and the indent specifies the indentation size for nested structures. The sort_keys is a boolean value. If it is true, then the output of dictionaries will be sorted by key.
stud_json = json.dumps(mydict, indent=2, sort_keys=True)
print(stud_json)
Complete Code: Convert MongoDB Document to JSON
Here, we have merged the above code that we explained in chunks to convert MongoDB document data to JSON using the Python programming language.
import pymongo
import json
client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client["school"]
mycol = mydb["students"]
class create_dict(dict):
# __init__ function
def __init__(self):
self = dict()
# Function to add key:value
def add(self, key, value):
self[key] = value
mydict = create_dict()
i = 1
for y in mycol.find():
mydict.add(i, ({"name":y['name'],"age":y['age'],"section":y['section']}))
i = i+1
stud_json = json.dumps(mydict, indent=2, sort_keys=True)
print(stud_json)
The above code returns the following output in JSON format-
Related Articles
Display data from MongoDB in HTML table using PythonInsert XML data to MongoDB using Python
Insert JSON data into MongoDB using Python
CRUD operations in Python using MongoDB connector
Write Python Pandas Dataframe to CSV
Quick Introduction to Python Pandas
Python Pandas DataFrame
Python3 Tkinter Messagebox
Python get visitor information by IP address
Python Webbrowser
Python Tkinter Overview and Examples
Python Turtle Graphics Overview
Factorial Program in Python
Python snake game code with Pygame
Python JSON Tutorial - Create, Read, Parse JSON file
Python convert xml to dict
Python convert dict to xml