2017-09-25 172 views
0

我認爲查詢是正確的,但仍然是錯誤。pymongo錯誤:過濾器必須是dict,bson.son.SON或從collections繼承的其他類型的實例。映射

findQ = {"fromid": wordid}, {"toid":1}   
    res= self.db.wordhidden.find(findQ) 

但是,find_one(findQ)起作用。所以我找不到錯誤的東西。 我使用python 3.6和pymongo。 這裏是我的代碼:

def getallhiddenids(self,wordids,urlids): 
    l1={} 
    for wordid in wordids: 
    findQ = {"fromid": wordid}, {"toid":1} 
    res= self.db.wordhidden.find(findQ) 
    for row in res: l1[row[0]]=1 
    for urlid in urlids: 
    findQ = {"toid": urlid}, {"fromid":1} 
    res= self.db.hiddenurl.find(findQ) 

這是一個錯誤:

Traceback (most recent call last): 
    File "C:\Users\green\Desktop\example.py", line 9, in <module> 
    neuralnet.trainquery([online], possible, notspam) 
    File "C:\Users\green\Desktop\nn.py", line 177, in trainquery 
    self.setupnetwork(wordids,urlids) 
    File "C:\Users\green\Desktop\nn.py", line 105, in setupnetwork 
    self.hiddenids=self.getallhiddenids(wordids,urlids) 
    File "C:\Users\green\Desktop\nn.py", line 93, in getallhiddenids 
    res= self.db.wordhidden.find(findQ) 
    File "C:\Users\green\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\pymongo\collection.py", line 1279, in find 
    return Cursor(self, *args, **kwargs) 
    File "C:\Users\green\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\pymongo\cursor.py", line 128, in __init__ 
    validate_is_mapping("filter", spec) 
    File "C:\Users\green\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\pymongo\common.py", line 400, in validate_is_mapping 
    "collections.Mapping" % (option,)) 
TypeError: filter must be an instance of dict, bson.son.SON, or other type 
that inherits from collections.Mapping 
+0

我還不是很瞭解pymongo。這就是說,findQ是一個元組。你可以傳遞一個元組到find()方法嗎? –

回答

0

find_one(findQ) works

這個錯誤是因爲PyMongo find()需要一個字典或bson.son對象。你傳入的是一個Python元組對象,形式爲({"fromid": wordid}, {"toid":1})。你可以通過調用下面的方法find()更正此:

db.wordhidden.find({"fromid": wordid}, {"toid": 1}) 

技術上你的find_one()調用也不起作用。只是參數過濾器已被find_one()更改。見find_one() L1006-1008。它基本上將你的元組過濾器格式化爲:

{'_id': ({"fromid": wordid}, {"toid":1}) } 

上面將(不應該)返回任何匹配在你的集合。

替代你在做什麼,你可以在過濾器參數保存到兩個變量,例如:

filterQ = {"fromid": wordid} 
projectionQ = {"toid": 1} 
cursor = db.wordhidden.find(filterQ, projectionQ) 
相關問題