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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25163658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:49:18  来源:igfitidea点击:

MongoDB return True if document exists

pythonmongodbpymongotornado-motor

提问by user94628

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.

如果用户 ID 已经存在,我想返回 true,否则从我的集合中返回 false。我有这个函数,但它总是返回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?

如果用户 id 已经存在,我怎样才能让这个函数只返回 true?

采纳答案by Philipp

Note:This answer is outdated. More recent versions of MongoDB can use the far more efficient method db.collection.countDocuments. See the answerby Xavier Guihot for a better solution.

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

finddoesn't return a boolean value, it returns a cursor. To check if that cursor contains any documents, use the cursors count-method.

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

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

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

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})

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

回答by A. Jesse Jiryu Davis

If you're using Motor, find() doesn't do any communication with the database, it merely creates and returns a MotorCursor:

如果您使用 Motor,则 find() 不会与数据库进行任何通信,它只会创建并返回一个 MotorCursor:

http://motor.readthedocs.org/en/stable/api/motor_collection.html#motor.MotorCollection.find

http://motor.readthedocs.org/en/stable/api/motor_collection.html#motor.MotorCollection.find

Since the MotorCursor is not None, Python considers it a "true" value so your function returns True. If you want to know if at least one document exists that matches your query, try find_one():

由于 MotorCursor 不是 None,Python 将其视为“真”值,因此您的函数返回 True。如果您想知道是否存在至少一个与您的查询匹配的文档,请尝试 find_one():

@gen.coroutine
def alreadyExists(newID):
    doc = yield db.mycollection.find_one({'UserIDS': { "$in": newID}})
    return bool(doc)

Notice you need a "coroutine" and "yield" to do I/O with Tornado. You could also use a callback:

请注意,您需要一个“协程”和“收益”来使用 Tornado 进行 I/O。您还可以使用回调:

def alreadyExists(newID, callback):
    db.mycollection.find_one({'UserIDS': { "$in": newID}}, callback=callback)

For more on callbacks and coroutines, see the Motor tutorial:

有关回调和协程的更多信息,请参阅电机教程:

http://motor.readthedocs.org/en/stable/tutorial.html

http://motor.readthedocs.org/en/stable/tutorial.html

If you're using PyMongo and not Motor, it's simpler:

如果您使用的是 PyMongo 而不是 Motor,则更简单:

def alreadyExists(newID):
    return bool(db.mycollection.find_one({'UserIDS': { "$in": newID}}))

Final note, MongoDB's $in operator takes a list of values. Is newID a list? Perhaps you just want:

最后要注意的是,MongoDB 的 $in 运算符采用值列表。newID 是一个列表吗?也许你只是想要:

find_one({'UserIDS': newID})

回答by Prateek Jha

I guess am very late to post the solution. Anyways i have encountered same problem today and following worked for me. Hope this help to others.

我想发布解决方案已经很晚了。无论如何,我今天遇到了同样的问题,以下对我有用。希望这对其他人有帮助。

return db.mycollection.find({'UserIDS': newID}).count > 0

回答by Deepak Shingan

One liner solution in mongodb query

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

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

回答by siva kumar

This worked for me

这对我有用

result = num.find({"num": num}, { "_id": 0 }) 
if result.count() > 0:  
   return
else:
   num.insert({"num": num, "DateTime": DateTime })

回答by Xavier Guihot

Starting Mongo 4.0.3/PyMongo 3.7.0, we can use count_documents:

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

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

Used with the optional parameter limit, this provides a way to find if there is at least one matching occurrence.

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

Limiting the number of matching occurrences makes the collection scan stop as soon as a match is found instead of going through the whole collection.

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



Note that this can also be written as follow since 1is interpreted as Truein a python condition:

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

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


In earlier versions of Mongo/Pymongo, countcould be used (deprecated and replaced by count_documentsin Mongo 4):

Mongo/ 的早期版本中Pymongocount可以使用(已弃用并由count_documentsin替换Mongo 4):

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