I am trying to dump a collection to .json file and looked into previous discussions and the solution doesn't seem to work for some reason.
Link : How to dump a collection to json file using pymongo
I am using Python3 and following the solution :
import json
import simplejson
from bson.json_util import dumps
import pymongo
from pymongo import MongoClient
client = MongoClient()
db = client.db_name
collection = db.collection_name
def writeToJSONFile(collection):
cursor = collection.find({})
file = open("collection.json", "w")
file.write('[')
qnt_cursor = 0
for document in cursor:
qnt_cursor += 1
num_max = cursor.count()
if (num_max == 1):
file.write(json.dumps(document, indent=4, default=json_util.default))
elif (num_max >= 1 and qnt_cursor <= num_max-1):
file.write(json.dumps(document, indent=4, default=json_util.default))
file.write(',')
elif (qnt_cursor == num_max):
file.write(json.dumps(document, indent=4, default=json_util.default))
file.write(']')
return file
NameError: name 'json_util' is not defined