如果文档存在,则MongoDB返回True [英] MongoDB return True if document exists

查看:342
本文介绍了如果文档存在,则MongoDB返回True的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆