遍历 mongodb 集合中单个键值的列表

iterating over a list of values of single key in a collection in mongodb

我在 mongodb 中存储了一组财务数据。每个公司符号都有其数据。问题是如何遍历集合并更改作为符号公司的键的值以打印出整个集合,这是我的公司列表 ['TSLA','TYO','C','LULU','DTV','SHS','ZNGA']这是我的鳕鱼return一家公司的数据:

   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)) 

如果我没理解错的话。您想要检索给定公司的 document/data。公司用符号示例表示 'TYSLA'.

如果这就是您所需要的。这是您的操作方法(假设每个符号都是唯一的)

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

上面会return一个字典。要访问您刚刚使用的文档中的元素:

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

现在要编辑利润属性,请使用 $set

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 

以上 return 是给定交易品种的全部数据。要 return 具体 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

希望对您有所帮助。