MongoServerError:计划执行器错误:聚合阶段'lookup'导致内存压力:估计大小200MB超过100MB限制
MongoServerError: PlanExecutor error: aggregation stage 'lookup' caused memory pressure: estimated size 200MB exceeds 100MB limit
ID: mongodb/aggregation-lookup-unwind-memory-pressure
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| mongodb 6.0 | active | — | — | — |
| mongodb 7.0 | active | — | — | — |
| mongodb 8.0 | active | — | — | — |
根因分析
在大型集合上使用$lookup和$unwind阶段导致中间结果超过100MB内存限制,通常是由于缺少索引或笛卡尔积连接。
English
A $lookup stage with $unwind on large collections exceeded the 100MB memory limit for intermediate results, often due to missing indexes or cartesian product joins.
官方文档
https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/#memory-considerations解决方案
-
Create an index on the foreign field used in $lookup: `db.orders.createIndex({ customerId: 1 })` to reduce the size of matched documents and avoid full collection scans. -
Restructure the pipeline: use $lookup with a pipeline to filter documents before joining, e.g., `{ $lookup: { from: 'orders', let: { custId: '$_id' }, pipeline: [ { $match: { $expr: { $eq: ['$customerId', '$$custId'] } } }, { $limit: 100 } ], as: 'orders' } }` to limit matched documents. -
Split the aggregation: perform $lookup in a separate aggregation, write results to an intermediate collection, then run $unwind on that smaller dataset.
无效尝试
常见但无效的做法:
-
85% 失败
allowDiskUse does not apply to intermediate results of $lookup before $unwind; it only helps for sorting and grouping stages after the join.
-
95% 失败
The 100MB limit is hard-coded for $lookup intermediate results and cannot be changed; attempting to set it has no effect.
-
70% 失败
While this may reduce memory, it changes the output structure; the root cause is the large join size, not the unwind itself.