MongoDB return True if document exists

后端 未结 6 1046
星月不相逢
星月不相逢 2020-12-14 01:39

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 alr         


        
6条回答
  •  伪装坚强ぢ
    2020-12-14 02:31

    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
    

提交回复
热议问题