5

I want to get count with Motor's diver but I got this error.

AttributeError: 'AsyncIOMotorCursor' object has no attribute 'count'

This is my code:

await MOTOR_CURSOR.users.find().count()
Valijon
  • 12,667
  • 4
  • 34
  • 67
Ali Hallaji
  • 3,712
  • 2
  • 29
  • 36
  • 1
    Haven't used Mongo in quite a while but what about [count_documents](https://motor.readthedocs.io/en/stable/api-tornado/motor_collection.html#motor.motor_tornado.MotorCollection.count_documents)? – Ionut Ticus Mar 29 '20 at 20:06

1 Answers1

7

MotorCollection.find() returns AsyncIOMotorCursor and it does not have count method. Instead, you should call MotorCollection.count_documents() instead.

await db.users.count_documents({'x': 1})

Also worth noting that what you're referring to as MOTOR_CURSOR is MotorDatabase instance, it would preferable to call it a db instance instead of a cursor to avoid confusion.

Wan B.
  • 18,367
  • 4
  • 54
  • 71
  • It's unacceptably slow. Unlike plain mongo's `count()` which return a result immediately. But the latter isn't seems available via the Motor :| – Pavel Vlasov Sep 22 '21 at 12:04
  • 1
    @PavelVlasov, the `count()` function is a legacy function that has been deprecated in all MongoDB client interfaces (i.e. `mongo`). It has been replaced by `count_document()` and `estimated_document_count()`. The legacy `count()` is essentially [estimated_document_count()](https://motor.readthedocs.io/en/stable/api-asyncio/asyncio_motor_collection.html?#motor.motor_asyncio.AsyncIOMotorCollection.estimated_document_count). – Wan B. Oct 12 '21 at 10:43