对象 MotorLatentCommandCursor 不能在“await”表达式中使用

Nat*_*tee 0 python tornado mongodb tornado-motor

在Tornado中使用motor连接mongodb

我创建了一个电机连接

import motor.motor_tornado
from tornado.web import RequestHandler
client = motor.motor_tornado.MotorClient('mongodb://xxx')

class BaseHandler(RequestHandler):
    @property
    def db(self):
        return client['realtime-test']

class Account(BaseHandler):
    async def get(self,*args,**kwargs):
        all_user = await self.db.account.aggregate([
            {'$match': {'status': 1}},
            {'$group': {'_id':''}}
        ])
        print(all_user)
Run Code Online (Sandbox Code Playgroud)

当我开始时,我收到此消息:“对象 MotorLatentCommandCursor 不能在 'await' 表达式中使用”

不知道为什么~好像没什么问题

xyr*_*res 5

aggregate()方法返回一个可以在循环中使用的游标。您不能在await语句中使用它,因为它不是可等待的对象。

你会像这样使用它:

async def get(self,*args,**kwargs):
    cursor = self.db.account.aggregate([
        {'$match': {'status': 1}},
        {'$group': {'_id':''}}
    ])

    all_user = []

    async for doc in cursor: 
        all_user.append(doc)

    print(all_user)
Run Code Online (Sandbox Code Playgroud)