Import CSV file data into MongoDB using Python

In this tutorial, we will share with you how to import CSV file data into MongoDB using Python. While developing an application using Python, sometimes we need to insert CSV data into the MongoDB database. Inserting CSV data to MongoDB is very easy in Python. We just need t read the CSV file and then connect to MongoDB to insert data. We will use CSV built-in module to read CSV files. We will use module pymongo to connect with the MongoDB client and insert data.
So let’s start firstly Install PyMongo Module :
Install PyMongo Module
As we need to connect with the MongoDB client, so we need to install pymongo module using below command.
Connect to MongoDB
We will import module pymongo to connect with MongoDB to insert records.
We will configure MongoDB connection details and connection to the database and collection to insert records.
Reading CSV File
As we will insert CSV file data to the MongoDB. So we will import the CSV module at the top of the file to read the CSV file.
We will CSV file employee using DictReader() method. The DictReader() function returns a csv reader object.
We will iterate over CSV reader object and create JSON data to insert multiple records into MongoDB.
Insert data into MongoDB
We will insert json row data into MongoDB.
Final code to insert CSV data into MongoDB
Now you can insert the JSON in your MongoDB database.