MongoDB return True if document exists

血红的双手。 提交于 2019-11-27 13:47:26

问题


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?


回答1:


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 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.

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




回答2:


Starting Mongo 4.0.3/PyMongo 3.7.0, we can use 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.

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 1 is interpreted as True in a python condition:

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

In earlier versions of Mongo/Pymongo, count could be used (deprecated and replaced by count_documents in Mongo 4):

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



回答3:


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

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():

@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:

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

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

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:

find_one({'UserIDS': newID})



回答4:


One liner solution in mongodb query

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



回答5:


This worked for me

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



回答6:


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


来源:https://stackoverflow.com/questions/25163658/mongodb-return-true-if-document-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!