close

How to import JSON file to MongoDB using Python

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to import JSON file to MongoDB using Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to import JSON file to MongoDB using Python?

  1. How to import JSON file to MongoDB using Python?

    You can read data from file and insert it into collection using insert_one method:

  2. import JSON file to MongoDB using Python

    You can read data from file and insert it into collection using insert_one method:

Method 1

You can read data from file and insert it into collection using insert_one method:

import json
from pymongo import MongoClient

client = MongoClient('localhost', 27017)
db = client['countries_db']
collection_currency = db['currency']

with open('currencies.json') as f:
    file_data = json.load(f)

# if pymongo < 3.0, use insert()
collection_currency.insert(file_data)
# if pymongo >= 3.0 use insert_one() for inserting one document
collection_currency.insert_one(file_data)
# if pymongo >= 3.0 use insert_many() for inserting many documents
collection_currency.insert_many(file_data)

client.close()

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read