How to get count on MongoDB's Motor driver?

5k Views Asked by At

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()
1

There are 1 best solutions below

2
Wan B. On BEST ANSWER

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.