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.
To import a JSON file into MongoDB using Python, you can use the PyMongo library which is the official Python driver for MongoDB. Follow the steps below to import a JSON file into MongoDB:
Step 1: Install PyMongo If you haven’t installed PyMongo yet, you can install it using pip:
pip install pymongo
Step 2: Connect to MongoDB To connect to MongoDB, you need to specify the connection string and create a MongoClient object. The connection string contains the MongoDB server address and port number. Here is an example:
from pymongo import MongoClient # create a client instance of MongoClient client = MongoClient('mongodb://localhost:27017/')
Step 3: Load the JSON file Next, you need to load the JSON file into Python using the json library:
import json with open('file.json') as f: data = json.load(f)
Step 4: Insert data into MongoDB Finally, you can insert the data into MongoDB using the insert_many() method:
# select the database db = client.mydatabase # select the collection collection = db.mycollection # insert the data collection.insert_many(data)
This code will insert all the JSON objects in the file.json file into the mycollection collection in the mydatabase database.