如果文档存在,则MongoDB返回True

编程入门 行业动态 更新时间:2024-10-28 04:21:08
本文介绍了如果文档存在,则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

本文发布于:2023-10-18 03:02:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502885.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档   MongoDB   True

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!