MongoDB return True if document exists

后端 未结 6 1068
星月不相逢
星月不相逢 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:26

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

提交回复
热议问题