I'm making a MongoDB query where i both need to loop through my results and count the len of the result to see if i'm being returned an empty result.
Here is what i tried:
Record = db.mycol.find({"datetimeraw": dt.now().strftime('%Y%m%d%H%M')})
RecordLen = Record.count()
print('LEN IS':RecordLen)
for x in Record:
print(x)
This code works, but when i use it i get the following error: DeprecationWarning: count is deprecated. Use Collection.count_documents instead. The problem is that i cannot use count_documents(), since it will return an integer and not a list of results that i can loop through; i would have to make two queries in this case: one to count and one to retrieve the results, and i would like to avoid that. Is there any way to do this or can i only use a depecrated function?
In MongoDB .find() will always return a cursor, which can either be empty [] or an array of documents/dicts [{},{}].
As .count() can be used in three ways :
/** 1. Queries all docs based on filter and then returns no.of docs matches with query */
db.collection.find( { queryFilter } ).count()
/** 2. Returns no.of docs */
db.collection.count()
/** 3. Returns a cursor `results` */
results = db.collection.find( { queryFilter } )
results.count()
So first two options are similar to countdocuments() and estimateddocumentcount() (returns a number) but as you wanted to return the documents and also get the count on cursor similar to cursor.count() then you can do it in code by using len() method : len(list(results)).
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