pymongo错误:filter必须是dict,bson.son.SON或其他继承自collections.Mapping的类型的实例。

时间:2017-09-25 13:16:42

标签: python pymongo-3.x

我认为查询正确但仍然是错误。

    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

1 个答案:

答案 0 :(得分:1)

  

find_one(findQ)有效

错误是因为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)