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

FastAPI中Motor Client v3.1.1聚合分页allowDiskUse配置求助

解决Motor聚合分页时的内存超限问题

你的问题出在allowDiskUse的位置不对——它不是聚合管道里的阶段,而是aggregate()方法的参数,不能写到pipeline数组里。

正确的代码写法

把allowDiskUse=True作为参数传给aggregate()方法即可:

client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://<my-connection-string>/')
database = client.test_database
collection = database.test_collection
pipeline = [
    { "$facet": 
        {"items": 
            [{ "$match": { }},
            {"$sort": {"_id": -1}},
            { "$skip": pageskip },
            { "$limit": pagesize },
            ],
        "totalCount": [{ "$count": "count" }]}}
        ]

# 在这里添加allowDiskUse参数
cursor = collection.aggregate(pipeline, allowDiskUse=True)

补充说明

启用allowDiskUse后,MongoDB会将排序操作溢出到磁盘,解决内存超限的问题,但要注意:

  • 磁盘排序比内存排序慢,大量数据分页时性能会下降
  • 如果你分页的页码很大(比如几百上千页),$skip+$limit的方式本身效率很低,建议改用游标分页(基于上一页最后一条文档的_id或其他有序字段来查询),比如:
    # 假设上一页最后一条文档的_id是last_id
    pipeline = [
        { "$match": {"_id": {"$lt": last_id}}},
        { "$sort": {"_id": -1}},
        { "$limit": pagesize }
    ]
    
    这种方式不需要$skip,性能更稳定,也能避免内存超限问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:25:28