'TypeError: object of type 'Cursor' has no len()
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)
Solution 1:[1]
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.
Solution 2:[2]
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.
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | HuguesG |
