2016-02-02 35 views
0

我有一個存儲在mongodb中的財務數據集合。每個公司符號都有其數據。問題是如何迭代集合並更改作爲符號公司的關鍵字的價值以打印出整個集合,這是我的公司列表['TSLA','TYO','C','LULU' ,「數字電視」,「SHS」,「ZNGA」]這是我的鱈魚,其返回一個公司的數據:在mongodb中迭代集合中單個鍵的值列表

from pymongo import MongoClient 
    import csv 
    host = "localhost" 
    port = 27017 
    databaseName = "finance000" 
    collection_name = "income" 
    client = MongoClient(host, port) 
    database = client[databaseName] 
    collection = database[collection_name] 
    def finance_data(symbol): 
     Earnings_BeforeInterestAndTaxes = symbol['statement'[0]EarningsBeforeInterestAndTaxes']['content']            
     Total_Revenue = symbol['statement'][0]['TotalRevenue']['content'] 
     return Earnings_BeforeInterestAndTaxes,Total_Revenue 
i =collection.find({'symbol':'C'}) 

with open('D:/INCOMEdata.csv', "w") as output: 
writer = csv.writer(output, lineterminator='\n') 
for key in i : 
    print finance_data(key) 

    writer.writerow(finance_data(key)) 

回答

0

如果我理解正確的你。您想要檢索給定公司的文檔/數據。該公司由一個符號示例'TYSLA'表示。

如果這是你所需要的。這裏是你怎麼做(假設每個符號都是唯一的)

company_data = collection.find({'symbol':'TYSLA'}) 

上面將返回一個字典。要在文檔中訪問一個元素只需使用:

company_data['profit'] #profit is an example of an attribute name. You can use any attribute you like. 

假設你有多個公司使用相同的符號。如果你使用了上述命令。你會得到一個遊標。讓每家公司只是做一個for循環示例:

company_data = collection.find({'symbol':'TYSLA'}) 

我們循環:

for one in company_date: 
    print one['profit'] #python 2.7 

我們編輯例如盈利屬性使用$設置

collection.update_one({'symbol':'TYSLA'},{'profit':100}) 
發言權

以上將使TYSLA的公司利潤變爲100

更新

假設您有一個符號是['TSLA','TYO','C','LULU','DTV','SHS','ZNGA']的任何值的集合。獲取數據對於任何使用符號(假設符號包含的任何名稱(只有一個名字)的):你用$

爲:

collection.find({"$or":[ {'symbol':'TSLA},{'symbol':'TYO},... ]},{}) #the ... are the rest of the names you need 

以上的回報給定符號的整個數據。要返回的具體TOTAL_REVENUE和Earnings_BeforeInterestAndTaxes您使用以下命令:

collection.find({"$or":[ {'symbol':'TSLA},{'symbol':'TYO},... ]},{'Total_Revenue ':1,'Earnings_BeforeInterestAndTaxes ':1, _id:0 }) #if you remove _id it will always be returned 

我希望幫助。

+0

謝謝你的回覆。我需要的是遍歷整個集合並檢索所有給定的公司數據,即Total_Revenue和Earnings_BeforeInterestAndTaxes。我有一個關鍵是這些公司的象徵性和多重價值。我試過{符號':['TSLA','TYO','C','LULU','DTV','SHS','ZNGA']}但是沒有工作 –

+0

噢好吧,在這裏你將不得不使用$在我將更新我的回答 – ibininja

+0

$ in如果您使用的數組符號。我假設符號有一個名字,所以使用$或者。檢查我的更新 – ibininja