Trying to input csv data in mongodb using python.i'm for beginners for python and mongodb .. i used the following code
import csv import json import pandas as pd import sys, getopt, pprint from pymongo import MongoClient #CSV to JSON Conversion csvfile = open('C://test//final-current.csv', 'r') jsonfile = open('C://test//6.json', 'a') reader = csv.DictReader( csvfile ) header= [ "S.No", "Instrument Name", "Buy Price", "Buy Quantity", "Sell Price", "Sell Quantity", "Last Traded Price", "Total Traded Quantity", "Average Traded Price", "Open Price", "High Price", "Low Price", "Close Price", "V" ,"Time"] #fieldnames=header output=[] for each in reader: row={} for field in header: row[field]=each[field] output.append(row) json.dump(output, jsonfile, indent=None, sort_keys=False , encoding="UTF-8") mongo_client=MongoClient() db=mongo_client.october_mug_talk db.segment.drop() data=pd.read_csv('C://test//6.json', error_bad_lines=0) df = pd.DataFrame(data) records = csv.DictReader(df) db.segment.insert(records)
but the output is in this format
{ "_id" : ObjectId("54891c4ffb2a0303b0d43134"), "[{\"AverageTradedPrice\":\"0\"" : "BuyPrice:\"349.75\"" } { "_id" : ObjectId("54891c4ffb2a0303b0d43135"), "[{\"AverageTradedPrice\":\"0\"" : "BuyQuantity:\"3000\"" } { "_id" : ObjectId("54891c4ffb2a0303b0d43136"), "[{\"AverageTradedPrice\":\"0\"" : "ClosePrice:\"350\"" } { "_id" : ObjectId("54891c4ffb2a0303b0d43137"), "[{\"AverageTradedPrice\":\"0\"" : "HighPrice:\"0\"" }
Actually, I want the output to be pleasant for one id, all other fields should be displayed as subtypes for example:
_id" : ObjectId("54891c4ffb2a0303b0d43137") AveragetradedPrice :0 HighPrice:0 ClosePrice:350 buyprice:350.75
Please help me Out.Thanks in advance