如何将 Motor Latent CommandCursor 转换为列表
How to convert MotorLatentCommandCursor to list
我在我的 django 项目中使用 mongoDB 的电机驱动程序,但我无法将我的数据(作为游标来自数据库)转换为列表,这是我的代码:
documents = db.factor.aggregate([{"$limit": 3},
{"$lookup": {"from": "subfactor", "localField": "_id", "foreignField": "factor_id", "as": "subfactor"}}])
for d in await list(documents):
print(d)
和错误:
File "/usr/lib/python3.8/asyncio/runners.py", line 43, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.8/asyncio/base_events.py", line 595, in run_until_complete
self.run_forever()
File "/usr/lib/python3.8/asyncio/base_events.py", line 563, in run_forever
self._run_once()
File "/usr/lib/python3.8/asyncio/base_events.py", line 1808, in _run_once
event_list = self._selector.select(timeout)
File "/usr/lib/python3.8/selectors.py", line 468, in select
fd_event_list = self._selector.poll(timeout, max_ev)
我不了解 Motor,但快速查看他们的 docs 显示:
游标是异步可迭代的,所以你可以使用 async for 来迭代:
async for document in db.test_collection.find({'i': {'$lt': 2}}):
pprint.pprint(document)
您可以将其转换为具有异步列表理解的列表:
items = [x async for x in db.test_collection.find({'i': {'$lt': 2}})]
它们还有将游标转换为可等待列表的辅助函数:
items = await db.test_collection.find({'i': {'$lt': 2}}).to_list(length=100)
我在我的 django 项目中使用 mongoDB 的电机驱动程序,但我无法将我的数据(作为游标来自数据库)转换为列表,这是我的代码:
documents = db.factor.aggregate([{"$limit": 3},
{"$lookup": {"from": "subfactor", "localField": "_id", "foreignField": "factor_id", "as": "subfactor"}}])
for d in await list(documents):
print(d)
和错误:
File "/usr/lib/python3.8/asyncio/runners.py", line 43, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.8/asyncio/base_events.py", line 595, in run_until_complete
self.run_forever()
File "/usr/lib/python3.8/asyncio/base_events.py", line 563, in run_forever
self._run_once()
File "/usr/lib/python3.8/asyncio/base_events.py", line 1808, in _run_once
event_list = self._selector.select(timeout)
File "/usr/lib/python3.8/selectors.py", line 468, in select
fd_event_list = self._selector.poll(timeout, max_ev)
我不了解 Motor,但快速查看他们的 docs 显示:
游标是异步可迭代的,所以你可以使用 async for 来迭代:
async for document in db.test_collection.find({'i': {'$lt': 2}}):
pprint.pprint(document)
您可以将其转换为具有异步列表理解的列表:
items = [x async for x in db.test_collection.find({'i': {'$lt': 2}})]
它们还有将游标转换为可等待列表的辅助函数:
items = await db.test_collection.find({'i': {'$lt': 2}}).to_list(length=100)