You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用TaskGroup结合Motor Aggregate时遭遇StopAsyncIteration错误

使用TaskGroups迭代Motor聚合结果时出现StopAsyncIteration错误

在使用asyncio.TaskGroups并行迭代Motor的聚合查询结果时,会抛出StopAsyncIteration错误,但串行执行或先串行后并行的场景下无此问题。

复现代码

import asyncio

from motor.motor_asyncio import AsyncIOMotorClient


def create_aggregate():
    client = AsyncIOMotorClient("mongodb://localhost:27017")
    collection = client["test"]["test"]

    return collection.aggregate([])

async def get_next(agg):
    item = await agg.next()
    print(item)

async def run_1_success():
    agg = create_aggregate()
    
    await get_next(agg)

async def run_2_success():
    agg = create_aggregate()
    await get_next(agg)

    async with asyncio.TaskGroup() as tg:
        tg.create_task(get_next(agg))
        tg.create_task(get_next(agg))

async def run_3_error():
    agg = create_aggregate()

    async with asyncio.TaskGroup() as tg:
        tg.create_task(get_next(agg))
        tg.create_task(get_next(agg))

运行情况

  • 执行asyncio.run(run_1_success())或asyncio.run(run_2_success()),迭代正常完成
  • 执行asyncio.run(run_3_error()),抛出StopAsyncIteration错误

环境信息

  • Python 3.12.2 (tags/v3.12.2:6abddd9, Feb 6 2024, 21:26:36) [MSC v.1937 64 bit (AMD64)]
  • Motor 3.4.0
  • PyMongo 4.6.2
  • Windows 10 64位

内容的提问来源于stack exchange,提问作者minimino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 05:52:10