Python Forum

Full Version: Load JSON file data into mongodb using pymongo
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to load JSON data into MongoDB using pymongo library.

I found that JSON data can be directly load using mongoimport using the command prompt using the following command.

mongoimport --db myTestDB --collection myTestCollection_Table --jsonArray --file D:\path\myJson1.json

But I want to how to do this using python pymongo library(without specifying keys or values separately in the code. as it is done in the above method)

I managed to load the JSON file data into python.

with open(r'D:\path\example_2.json', 'r') as f:
    data = json.load(f)
Appreciate if you can give some inputs on how to load above data into mongodb using python.
Managed to solve my issue.

import pymongo 
mng_client = pymongo.MongoClient('localhost', 27017)
mng_db = mng_client['UNSdatabase'] # Replace mongo db name
collection_name = 'UNS_Collection2' # Replace mongo db collection name
db_cm = mng_db[collection_name]

# Get the data from JSON file
with open(r'D:\path\example_2.json', 'r') as data_file:
    data_json = json.load(data_file)

#Insert Data
db_cm.remove()
db_cm.insert(data_json)

# Query data
db_cm.UNS_Collection2.find().pretty()