TypeError: object of type 'Cursor' has no len()

Question:

I get this error:

TypeError: object of type ‘Cursor’ has no len()

when I try to execute:

reply = db['test'].find({"date":{"$gt":date_query}} ,{"date":1,"route_id":1,"loc":1,"_id":0})

length = len(reply)
Asked By: maniac_user

||

Answers:

The pymongo cursor has a method count() which will return what you’re looking for:

reply = db['test'].find(
  {"date":{"$gt":date_query}},
  {"date":1,"route_id":1,"loc":1,"_id":0}
)

length = reply.count()
Answered By: cacahootie

Yes, count will do the work for you.

length = reply.count() 

or

length = reply.count(with_limit_and_skip=False)

had to suffer a lot coz length = count(reply) also did not work. Since I’m not allowed to comment yet, thought to leave this answer. Hope this will help somebody to save some time.

Answered By: Wenuka

Starting Mongo 4.0.3/PyMongo 3.7.0, you could alternatively use count_documents instead of count on a cursor:

db.collection.count_documents({ "a": 2 })
# where { "a": 2 } is whatever filtering query

db.collection.count_documents is the alternative to the now deprecated db.collection.count.

Answered By: Xavier Guihot

TLDR:
count is deprecated. Use reply.explain().get("executionStats", {}).get("nReturned")

https://pymongo.readthedocs.io/en/stable/api/pymongo/cursor.html#pymongo.cursor.Cursor.explain

I’m updating this thread since I was searching for this answer.

You will also see answers telling you to do len(list(reply)). This is of course not recommended since it loads all documents at once in memory. Advantages of cursors is to load each document only when needed, and not to keep it in memory if it is useless. For instance, in my usecase, putting it in a list makes my jupyter kernel explode.

Answered By: HuguesG

If you are trying on MySQL;

len(results.fetchall())
Answered By: Ömer ÇELEBÄ°