Python Forum
Load JSON file data into mongodb using pymongo
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Load JSON file data into mongodb using pymongo
#1
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.

Attached Files

.json   example_2.json (Size: 947 bytes / Downloads: 500)
Reply
#2
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()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  encrypt data in json file help jacksfrustration 1 210 Mar-28-2024, 05:16 PM
Last Post: deanhystad
  Load data in Oracle muzokh 0 251 Mar-08-2024, 11:19 PM
Last Post: muzokh
  parse json field from csv file lebossejames 4 737 Nov-14-2023, 11:34 PM
Last Post: snippsat
  JSON Dump and JSON Load foxholenoob 8 1,108 Oct-12-2023, 07:21 AM
Last Post: foxholenoob
  Using pyodbc&pandas to load a Table data to df tester_V 3 819 Sep-09-2023, 08:55 PM
Last Post: tester_V
  Python Script to convert Json to CSV file chvsnarayana 8 2,519 Apr-26-2023, 10:31 PM
Last Post: DeaD_EyE
  Loop through json file and reset values [SOLVED] AlphaInc 2 2,126 Apr-06-2023, 11:15 AM
Last Post: AlphaInc
  Converting a json file to a dataframe with rows and columns eyavuz21 13 4,438 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
  validate large json file with millions of records in batches herobpv 3 1,275 Dec-10-2022, 10:36 PM
Last Post: bowlofred
  Read nested data from JSON - Getting an error marlonbown 5 1,368 Nov-23-2022, 03:51 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020