2014-12-11 9 views
5

Cercando di spingere i dati csv in MongoDB usando python.i'm un principiante a Python & mongodb..i utilizzato il seguente codicecome spingere un dato csv MongoDB usando pitone

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) 

ma l'uscita è data in questo formato

/* 0 */ 
{ 
    "_id" : ObjectId("54891c4ffb2a0303b0d43134"), 
    "[{\"AverageTradedPrice\":\"0\"" : "BuyPrice:\"349.75\"" 
} 

/* 1 */ 
{ 
    "_id" : ObjectId("54891c4ffb2a0303b0d43135"), 
    "[{\"AverageTradedPrice\":\"0\"" : "BuyQuantity:\"3000\"" 
} 

/* 2 */ 
{ 
    "_id" : ObjectId("54891c4ffb2a0303b0d43136"), 
    "[{\"AverageTradedPrice\":\"0\"" : "ClosePrice:\"350\"" 
} 

/* 3 */ 
{ 
    "_id" : ObjectId("54891c4ffb2a0303b0d43137"), 
    "[{\"AverageTradedPrice\":\"0\"" : "HighPrice:\"0\"" 
} 

in realtà voglio l'uscita come singolo id tutti gli altri campi dovrebbero essere mostrato come sottotipi ad esempio:

_id" : ObjectId("54891c4ffb2a0303b0d43137") 
    AveragetradedPrice :0 
    HighPrice:0 
    ClosePrice:350 
    buyprice:350.75 

Please help me Out.Thanks in anticipo

+0

output.append (riga) => db.segment.insert (riga) – anhlc

+0

ma se sto spingendo direttamente a MongoDB, produce InvalidDocument: chiave 'S.No' non deve contenere '.' – Viswanathan

+0

Crea un'intestazione come una dict per mappare s.no as s_no in modo che sia accetabile come chiave json – anhlc

risposta

5

Grazie per i suggestion.This uno è il codice corretto:

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') 
reader = csv.DictReader(csvfile) 
mongo_client=MongoClient() 
db=mongo_client.october_mug_talk 
db.segment.drop() 
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"] 

for each in reader: 
    row={} 
    for field in header: 
     row[field]=each[field] 

    db.segment.insert(row) 
-1

C'è un modo migliore con il minor numero di importazioni, a patto di avere una riga di intestazione nel tuo CSV.

from pymongo import MongoClient 
import csv 

# DB connectivity 
client = MongoClient('localhost', 27017) 
db = client.db 
collection = db.collection 

# Function to parse csv to dictionary 
def csv_to_dict(): 
    reader = csv.DictReader(open(FILEPATH)) 
    result = {} 
    for row in reader: 
     key = row.pop('First_value') 
     result[key] = row 
    return query 

# Final insert statement 
db.collection.insert_one(csv_to_dict()) 

Speranza che aiuta

Problemi correlati