症状
在遍历大型结果集中途出现 MongoServerError: cursor id ... not found。它与逐文档处理缓慢或长时间暂停相关。
诊断
为迭代计时并调整批量:
const cursor = coll.find({}).batchSize(1000);
for await (const doc of cursor) {
await slowProcess(doc); // ensure gaps stay under the cursor timeout
}
若任意暂停超过约 10 分钟,服务器就会回收该游标。
修复
增大批量,或基于索引键分页:
// page by _id to avoid a long-lived server cursor
let last = null;
while (true) {
const page = await coll.find(last ? { _id: { $gt: last } } : {})
.sort({ _id: 1 }).limit(1000).toArray();
if (!page.length) break;
for (const d of page) await slowProcess(d);
last = page[page.length - 1]._id;
}
验证
在大型集合上运行该任务;它能完成且不报 CursorNotFound,并恰好处理每个文档一次。