Prerequisites: MongoDB Python Basics
This article is about converting the PyMongo Cursor to JSON. Functions like find() and find_one() returns the Cursor instance.
Let%u2019s begin:
from pymongo import MongoClient from bson.json_util import dumps
client = MongoClient(%u2018localhost%u2019, 27017)
mydatabase = client.name_of_the_database
collection_name = mydatabase.name_of_collection
cursor = collection_name.find()
list_cur = list(cursor)
Now, converting the list_cur to the JSON using the method dumps() from bson.json_util
json_data = dumps(list_cur)
You can now save it to the file or can use it in the program using loads() function
Python code:
# Python Program for # demonstrating the # PyMongo Cursor to JSON # Importing required modules from pymongo import MongoClient from bson.json_util import dumps, loads # Connecting to MongoDB server # client = MongoClient('host_name', # 'port_number') client = MongoClient('localhost', 27017) # Connecting to the database named # GFG mydatabase = client.GFG # Accessing the collection named # gfg_collection mycollection = mydatabase.College # Now creating a Cursor instance # using find() function cursor = mycollection.find() # Converting cursor to the list # of dictionaries list_cur = list(cursor) # Converting to the JSON json_data = dumps(list_cur, indent = 2) # Writing data to file data.json with open('data.json', 'w') as file: file.write(json_data)
output:
Comments