4

我认为查询是正确的,但仍然是一个错误。

    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
4

1 回答 1

3

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)
于 2017-09-27T02:33:55.210 回答