mongodb报错:com.mongodb.MongoCursorNotFoundException

环境版本

mongodb版本:4.0.1
mongodb-driver: 3.6.4

问题描述

由于工作需要,线上mongodb中的部分集合需要添加一些新的字段。核心代码如下:

MongoCollection input = mongoDatabase.getCollection(inputCollection);
MongoCollection output = mongoDatabase.getCollection(outputCollection);

FindIterable findIterable = input.find();
MongoCursor mongoCursor = findIterable.iterator();
 while(mongoCursor.hasNext()){
     Document outputDocument = new Document();
     Document document = mongoCursor.next();
     for (String key: document.keySet()) {
     //.........
     // 添加字段,具体不列出
         }
         outputDocument.append(key, document.get(key));
     }
     output.insertOne(outputDocument);
 }

在线上运行一段时间后,程序报出如下异常:

Exception in thread "main" com.mongodb.MongoCursorNotFoundException: Query failed with error code -5 and error message 'Cursor 5267179983494953089 not found on server 74.7.8.96:27017' on server 74.7.8.96:27017
        at com.mongodb.operation.QueryHelper.translateCommandException(QueryHelper.java:27)
        at com.mongodb.operation.QueryBatchCursor.getMore(QueryBatchCursor.java:229)
        at com.mongodb.operation.QueryBatchCursor.hasNext(QueryBatchCursor.java:115)
        at com.mongodb.client.internal.MongoBatchCursorAdapter.hasNext(MongoBatchCursorAdapter.java:54)
        at com.zhishen.TestJoin.main(TestJoin.java:64)

异常显示是游标超时,通过相关资料得知mongodb 游标维持时间默认是10分钟,那么只需要修改游标永不超时就可以解决这个问题。

解决方案

MongoCollection input = mongoDatabase.getCollection(inputCollection);
MongoCollection output = mongoDatabase.getCollection(outputCollection);

//设置游标永不超时
FindIterable findIterable = input.find().noCursorTimeout(true);
MongoCursor mongoCursor = findIterable.iterator();
 while(mongoCursor.hasNext()){
     Document outputDocument = new Document();
     Document document = mongoCursor.next();
     for (String key: document.keySet()) {
     //.........
     // 添加字段,具体不列出
         }
         outputDocument.append(key, document.get(key));
     }
     output.insertOne(outputDocument);
 }

然后打包上传,重新执行。游标超时的问题再也没出现,完美解决。

你可能感兴趣的:(mongodb)