As the title suggests, I am trying to use count()
with a find()
on a collection but it keeps throwing the error AttributeError: 'Cursor' object has no attribute 'count'
.
For reference, I went through this question but count_documents()
seems to be tehre for colelctions themselves, and not cursors. The other option mentioned was len(list(cursor))
but I can't use that as it consumes the cursor itself (can't iterate over it after this). I went through a couple more answers, but these seem to be the main ways out.
Moreover, my pymongo version is 4.3.3
which can't be changed due to some restrictions.
Is there any operation I can perform directly on Cursor
which doesn't consume it?
def temp(col):
return col.find().count()
print(temp(collection))
Thanks!
list()
will exhaust the cursor, but save its ouput to a variable and you can access it multiple times, e.g.
records = list(col.find())
num_records = len(records)
for record in records:
# do stuff