如果用户 ID 已经存在,我想返回 true,否则从我的集合中返回 false。我有这个函数,但它总是返回 True
。
def alreadyExists(newID):
if db.mycollection.find({'UserIDS': { "$in": newID}}):
return True
else:
return False
如果用户 id 已经存在,我怎样才能让这个函数只返回 true?
最佳答案
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
不返回 bool 值,它返回 cursor .要检查该游标是否包含任何文档,请使用游标的 count
方法:
if db.mycollection.find({'UserIDS': { "$in": newID}}).count() > 0
如果 newID
不是数组,则不应使用 $in
运算符。你可以简单地做 find({'UserIDS': newID})
.
关于python - 如果文档存在,MongoDB 返回 True,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25163658/