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?
In MongoDB, we can check the existence of the field in the specified collection using the $exists operator. When the value of $exists operator is set to true, then this operator matches the document that contains the specified field(including the documents where the value of that field is null).
Which of the following method returns true if the cursor has documents? Explanation: hasNext() returns true if the cursor returned by the db.
The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.
MongoDB fetch documents containing 'null' If we want to fetch documents from the collection "testtable" which contains the value of "interest" is null, the following mongodb command can be used : >db. testtable. find( { "interest" : null } ).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With