pythonmongodbpymongomotorengine

How to get count on MongoDB's Motor driver?


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

Solution

  • 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.