Import Data in Mongo using Python


 PY-MONGO  DATA IMPORT


STEPS

  • Install Mongodb
    • Download MongoDB “https://www.mongodb.com/try/download/community
    • Install Mongodb from GUI
    • Download and Install Python “https://www.python.org/downloads/”
    • Install Py-Mongo from command prompt using command from command prompt  "python -m pip install pymongo"Collect Connection String
  • Install
    • Python [using command prompt "pip install notebook"]
    • Jupyter [using command prompt  "jupyter notebook"]

  • Data Preparation
    • Prepare a csv file with name “data.csv”
  • Install
    • Pymongo
  • Execute the Python code
    • Import the Data and Validate
    • Your CV is loaded successfully Mongodb database “CSV” , collection name “data_csv”
    • Connect to MongoDB compass and validate




Code To be Executed from Jupyter Notebook


/***********Python Code to Import Data***********/


#Install Py-Mongo from command prompt using below  "python -m pip install pymongo"
#My Local MongoDB string:  "mongodb://localhost:27017"

import csv
from pymongo import MongoClient

#Connect to MongoDB

client = MongoClient("mongodb://localhost:27017")

#Name of You database

db=client["CSV"]
#Name of your collection
collection =db["cdv_data_4"]
#Path to your CSV file
csv_file ="data.csv"

#Open the CSV File

with open(csv_file,"r") as file:
    reader=csv.DictReader(file)

    # Iterate each row in csv file

    for row in reader:

        #Insert rows in Mongodb

        collection.insert_one(row)

if (collection.count_documents({})==2):
    print("CSV data imported into MongoDB successfully !")
else:
    print("Something went Wrong!!")
/********************************/

saurabh Sinha mongodb SQLSERVER PYTHON



Validate The Data in MongoDB Compass


  • Connect with MongoDB using Local host
  • Check databases
  • Open database CSV
  • Check Collection CSV_data_4

saurabh sinha mongodb compass, python script





No comments:
Write comments

Please do not enter spam links

Meet US

Services

More Services