2017-02-08 137 views
1

我循環列表和循環裏面我環路一些文件這是從MongoDB中取出。但在輸出控制檯中,我只能看到一次迭代。 但外環工作正常。當我調試它進入外部循環內部但不進入內部循環。請幫助我。的Python for each循環不工作

client = MongoClient('mongodb://localhost:27017/') 
db = client['mydb'] 
documents = icps_db.user.find({}) 
name_set = ['john', 'marshal', 'ann' ...] 

    for name in name_set: 
     print(name) 
     for idx, document in enumerate(documents): 
      print (documents) 
      if name in document["filtered_words"]: 
       print ("Found " + name) 
      else: 
       print (name + " not found in document ") 

輸出 在第二次迭代中未達到行:打印(STR(IDX))。

john 
<pymongo.cursor.Cursor object at 0x7faed0ad0910> 
Found john 
<pymongo.cursor.Cursor object at 0x7faed0ad0910> 
john not found in document 
<pymongo.cursor.Cursor object at 0x7faed0ad0910> 
Found john 
<pymongo.cursor.Cursor object at 0x7faed0ad0910> 
john not found in document 
<pymongo.cursor.Cursor object at 0x7faed0ad0910> 
john not found in document 
<pymongo.cursor.Cursor object at 0x7faed0ad0910> 
Found john 
<pymongo.cursor.Cursor object at 0x7faed0ad0910> 
john not found in document 
<pymongo.cursor.Cursor object at 0x7faed0ad0910> 
Found john 
<pymongo.cursor.Cursor object at 0x7faed0ad0910> 
Found john 
<pymongo.cursor.Cursor object at 0x7faed0ad0910> 
john not found in document 
john 
marshal 
marshal 
+3

你確定'documents'是不是空的?也許首先打印這個集合。 –

+0

'文件'可能是空的。 – kazemakase

+0

文件肯定是空的 – Bodao

回答

2

的問題是在這裏:

documents = icps_db.user.find({}) 

你第一次迭代過documents光標用完之後。這是一個只讀的容器。你或者需要緩存結果,或者在內循環之前做documents.rewind()

要緩存結果呢:

documents = list(icps_db.user.find({})) 

我真的不知道MongoDB的,所以它可能是每個文檔都有某種形式的現場回調使用光標(我懷疑)。如果是這樣,簡單的緩存將無法工作。

另一種解決方案將是使用rewind()

倒帶此光標到其未計算的狀態。

復位該光標如果它已被部分或完全地進行評價。 光標上的任何選項都將保持有效。在此光標進行 未來的迭代將導致新的查詢被 發送到服務器,即使得到的數據已經被這個遊標檢索 。

使用它,像這樣:

for name in name_set: 
    documents.rewind() 
    for idx, document in enumerate(documents): 
     ...