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