How to import JSON File in MongoDB using Python?

Prerequisistes: MongoDB and Python, Working With JSON Data in Python

MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs.

JSON stands for JavaScript Object Notation. It is an open standard file format, and data interchange format with an extension “.json”, that uses human-readable text to store and transmit data objects consisting of attribute-value pairs and array data types.

Importing JSON file in MongoDB

To import a JSON file in MongoDB we have to first load or open the JSON file after that we can easily insert that file into the database or the collection. To load a JSON file we have to first import json in our code after that we can open the JSON file. When our file gets loaded or opened we can easily insert it into the collection and operate on that file. Let’s see the example for better understanding.

Example :



Sample JSON used:

python-mongodb-json

filter_none

edit
close

play_arrow

link
brightness_4
code

import json
from pymongo import MongoClient 
  
  
# Making Connection
myclient = MongoClient("mongodb://localhost:27017/"
   
# database 
db = myclient["GFG"]
   
# Created or Switched to collection 
# names: GeeksForGeeks
Collection = db["data"]
  
# Loading or Opening the json file
with open('data.json') as file:
    file_data = json.load(file)
      
# Inserting the loaded data in the Collection
# if JSON contains data more than one entry
# insert_many is used else inser_one is used
if isinstance(file_data, list):
    Collection.insert_many(file_data)  
else:
    Collection.insert_one(file_data)

chevron_right


Output:

python-json-to-mongodb

My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.