collection.find不将任何文档返回到数据帧

时间:2018-05-03 07:26:28

标签: python dataframe pymongo

将文档从MongoDb集合返回到数据框时遇到一些问题。下面的代码建立了与mongodb的连接:

from pymongo import MongoClient
# Connect to the Mongo client. MongoClient is the connection to the MongoDB instance on port 27017 on host hkgdlvasfj001.
client = MongoClient('hkgdlvasfj001', 27017)
# Access the bb i.e. access a collection in PyMongo
#display(client.database_names()) # all the db's in the db i.e. ['admin', 'config', 'gtm', 'local']
# Assign gtm database 
db = client.gtm

我可以成功从rfq集合中返回单个文档:

#display(db.collection_names()) # all collections in the d b i.e ['rfqs', 'trades']                             
# Search for the documents you want
display(db.rfqs.find_one({'Data.State': "Done"}))

Output: 
{'Data': {'Action': 'DealerAcceptOrder',
      'AllQ': '3.09',
      'AutoNegDealerMidValue': '3.09',
      'AutoNegDealerSpread': '0',
      'AutoNegDealerValue': '3.0846',
      'ClearingChannel': '',
      'ClearingCode': 'UNKNOWN',
      'ClearingHouse': 'UNKNOWN',

但是当我扩展标准时,我无法从我的数据框中获取任何文档

df = db.rfqs.find({'Data.State' : "Done",'Data.Ticker': "ACGB 3 3/4 04/21/37"})
display(df) 

返回<pymongo.cursor.Cursor at 0x84dc3c8>

在将文档分配给数据帧时,我需要做些什么吗?

1 个答案:

答案 0 :(得分:1)

这是因为您的find()返回了多个结果。这就是为什么它是pymongo.cursor.Cursor对象的原因。要恢复该对象,请尝试:

cursor= db.rfqs.find({'Data.State' : "Done",'Data.Ticker': "ACGB 3 3/4 04/21/37"})
df_list = list() # you can also create an empty dataframe here and concat the df to it later 
for doc in cursor:
    df_list.append(pd.DataFrame(doc))
    print(doc)

有关详细信息,请阅读this