MongoDB return True if document exists
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 cursor's count
method:
if db.mycollection.find({'UserIDS': { "$in": newID}}).count() > 0
If newID
is not an array you should not use the $in
operator. You can simply do find({'UserIDS': newID})
.
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