如果您使用的是 Motor,find() 不会与数据库进行任何通信,它只是创建并返回一个 MotorCursor:
http://motor.readthedocs.org/en/stable/api/motor_collection.html#motor.MotorCollection.find
由于 MotorCursor 不是 None,Python 将其视为“真”值,因此您的函数返回 True。如果您想知道是否存在至少一个与您的查询匹配的文档,请尝试 find_one():
@gen.coroutine
def alreadyExists(newID):
doc = yield db.mycollection.find_one({'UserIDS': { "$in": newID}})
return bool(doc)
请注意,您需要一个“协程”和“屈服”来使用 Tornado 进行 I/O。您还可以使用回调:
def alreadyExists(newID, callback):
db.mycollection.find_one({'UserIDS': { "$in": newID}}, callback=callback)
有关回调和协程的更多信息,请参阅 Motor 教程:
http://motor.readthedocs.org/en/stable/tutorial.html
如果您使用的是 PyMongo 而不是 Motor,则更简单:
def alreadyExists(newID):
return bool(db.mycollection.find_one({'UserIDS': { "$in": newID}}))
最后一点,MongoDB 的 $in 运算符采用一个值列表。newID 是一个列表吗?也许你只是想要:
find_one({'UserIDS': newID})