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 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 Connect to MongoDB We will import module
from pymongo import MongoClientpymongo
to connect with the MongoDB
client and insert
data.pymongo
module using below command.pymongo
to connect with MongoDB to insert records.
We will configure MongoDB connection details and connection to the database and collection to insert records.
mongoClient=MongoClient[] db=mongoClient.october_mug_talk db.segment.drop[] |
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.
csvfile=open['current.csv','r'] reader=csv.DictReader[csvfile] |
We will iterate over CSV reader object and create JSON data to insert multiple records into MongoDB.
foreachinreader: row={} forfield inheader: row[field]=each[field] |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import csv import json import pandas aspd import sys,getopt,pprint from pymongo import MongoClient #Conversion CSV to JSON csvfile =open['current.csv','r'] reader=csv.DictReader[csvfile] mongo_client=MongoClient[] db=mongo_client.october_mug_talk db.segment.drop[] header=["First Name","Last Name","Email","Mobile","Address","Date"] for eachinreader: row={} forfield inheader: row[field]=each[field] db.segment.insert[row] |