28

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

How could I get this function to only return true if a user id already exists?

4

7 回答 7

43

注意:此答案已过时。最新版本的 MongoDB 可以使用更有效的方法db.collection.countDocuments。请参阅Xavier Guihot的答案以获得更好的解决方案。

find不返回布尔值,它返回一个cursor。要检查该游标是否包含任何文档,请使用游标计数方法。

if db.mycollection.find({'UserIDS': { "$in": newID}}).count() > 0.

顺便说一句:newID 是一个数组吗?如果不是,则不应使用$in-operator。你可以简单地做find({'UserIDS': newID})

于 2014-08-06T15:18:20.847 回答
32

开始Mongo 4.0.3/ PyMongo 3.7.0,我们可以使用count_documents

if db.collection.count_documents({ 'UserIDS': newID }, limit = 1) != 0:
  # do something

与可选参数一起使用limit,这提供了一种查找是否存在至少一个匹配项的方法。

限制匹配出现的次数会使集合扫描在找到匹配项后立即停止,而不是遍历整个集合。


请注意,这也可以写成如下,因为1它被解释为TruePython 条件:

if db.collection.count_documents({ 'UserIDS': newID }, limit = 1):
  # do something

Mongo/的早期版本中Pymongocount可以使用(不推荐使用并替换为count_documentsin Mongo 4):

if db.collection.count({ 'UserIDS': newID }, limit = 1) != 0:
  # do something
于 2018-10-26T08:59:03.513 回答
3

如果您使用的是 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})
于 2014-08-06T15:20:58.287 回答
1
return db.mycollection.find({'UserIDS': newID}).count > 0
于 2017-05-13T14:47:27.463 回答
1

mongodb查询中的一种线性解决方案

db.mycollection.find({'UserIDS': { "$in": newID}}).count() > 0 ? true : false
于 2017-12-16T05:17:26.557 回答
0

这对我有用

result = num.find({"num": num}, { "_id": 0 }) 
if result.count() > 0:  
   return
else:
   num.insert({"num": num, "DateTime": DateTime })
于 2018-02-16T13:05:02.797 回答
-1
def alreadyExists(newID):
    retuen db.mycollection.find({'UserIDS': { "$in": newID}}).count() > 0
于 2022-02-22T16:01:47.320 回答