Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cursor.count() gives AttributeError in pymongo 4.3.3

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?

Sample code

def temp(col):
    return col.find().count()

print(temp(collection))

Thanks!

like image 201
Eagle Avatar asked Sep 02 '25 10:09

Eagle


1 Answers

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
like image 157
Belly Buster Avatar answered Sep 04 '25 00:09

Belly Buster