I need to check if a find
statement returns a non-empty query.
What I was doing was the following:
query = collection.find({"string": field})
if not query: #do something
Then I realized that my if
statement was never executed because find
returns a cursor, either the query is empty or not.
Therefore I checked the documentation and I find two methods that can help me:
count(with_limit_and_skip=False)
which (from the description):Returns the number of documents in the results set for this query.
It seems a good way to check, but this means that I need to count all the results in cursor to know if it is zero or not, right? A little bit expensive?
retrieved
which (from the description):The number of documents retrieved so far.
I tested it on an empty query set and it returns zero, but it's not clear what it does and I don't know if it's right for me.
So, which is the best way (best practice) to check if a find()
query returns an empty set or not? Is one of the methods described above right for this purpose? And what about performance? Are there other ways to do it?
Just to be clear: I need to know if the query is empty and I'd like to find the best way with the cursor with respect to performance and being pythonic.
count
need to rescan all results found to give me a number? – Longfacedlst = list(query)
and then checkif not lst: #do something
– Valdez