如果用户ID已经存在,我想返回true,否则返回false.我有此函数,但它始终返回True.
I want to return true if a userID already exists and false otherwise from my collection.I have this function but it always returns True.
def alreadyExists(newID): if db.mycollection.find({'UserIDS': { "$in": newID}}): return True else: return False如何让该函数仅在用户ID已经存在的情况下才返回true?
How could I get this function to only return true if a user id already exists?
推荐答案
注意:此答案已过时. MongoDB的最新版本可以使用效率更高的方法 db.collection.countDocuments .有关更好的解决方案,请参见Xavier Guihot的答案.
Note: This answer is outdated. More recent versions of MongoDB can use the far more efficient method db.collection.countDocuments. See the answer by Xavier Guihot for a better solution.
find不返回布尔值,而是返回光标.要检查该游标是否包含任何文档,请使用游标的count方法.
find doesn't return a boolean value, it returns a cursor. To check if that cursor contains any documents, use the cursors count-method.
if db.mycollection.find({'UserIDS': { "$in": newID}}).count() > 0.
顺便说一句:newID是数组吗?如果不是,则不应使用$in -operator.您只需执行find({'UserIDS': newID})
By the way: is newID an array? When it isn't, you should not use the $in-operator. You can simply do find({'UserIDS': newID})
更多推荐
如果文档存在,则MongoDB返回True
发布评论