mongoDB:游标notimeout设置不适用于java客户端

时间:2015-08-11 17:21:33

标签: java mongodb

我设置了一个' notimeout' java中dbcursor的选项:

    BasicDBObject nearbyQueries = new BasicDBObject("$gt", 0)
            .append("$lte", 2);
    DBCursor trueClassInstances = locationsCollection.find(new BasicDBObject("distanceFromHotel", nearbyQueries)).addOption(Bytes.QUERYOPTION_NOTIMEOUT).limit(100000);
    double counter = 0;
    int currentPresent = 0;
    for (DBObject instance : trueClassInstances) {

        ...
    }

即使我设置了此选项,也会抛出此异常:

Exception in thread "main" com.mongodb.MongoCursorNotFoundException: Query failed with error code -5 and error message 'Cursor 1876954464377 not found on server XXXXXX:27017' on server XXXXXXXX:27017
    at com.mongodb.connection.GetMoreProtocol.receiveMessage(GetMoreProtocol.java:115)
    at com.mongodb.connection.GetMoreProtocol.execute(GetMoreProtocol.java:68)
    at com.mongodb.connection.GetMoreProtocol.execute(GetMoreProtocol.java:37)
    at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:155)
    at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:219)
    at com.mongodb.connection.DefaultServerConnection.getMore(DefaultServerConnection.java:194)
    at com.mongodb.operation.QueryBatchCursor.getMore(QueryBatchCursor.java:197)
    at com.mongodb.operation.QueryBatchCursor.hasNext(QueryBatchCursor.java:93)
    at com.mongodb.MongoBatchCursorAdapter.hasNext(MongoBatchCursorAdapter.java:46)
    at com.mongodb.DBCursor.hasNext(DBCursor.java:152)
    at locationExtraction.DistanceClassification.FeatureAnalyzer.main(FeatureAnalyzer.java:27)

FeatureAnalyzer.java:27是for循环线。

此问题出现在具有类似设置的其他项目中......

我在做错了什么?也许我选择' for'循环而不是这种迭代会导致这种奇怪的行为吗?

while(cursor.hasNext())
{
      DBObject next = cursor.next();
}

由于

4 个答案:

答案 0 :(得分:1)

看起来您无法在时间限制内处理每个批次。尝试减少批量大小,以便在时间用完之前消耗每批次。这应该有所帮助。 cursor.addOption(com.mongodb.Bytes.QUERYOPTION_NOTIMEOUT).batchSize(100)

答案 1 :(得分:0)

所以问题解决了。 这很奇怪,但使用'for'循环迭代游标时出现问题。所以不要像我做的那样,使用'while'循环:

while(cursor.hasNext())
{
      DBObject next = cursor.next();
}

答案 2 :(得分:0)

在使用cursor.hasNext()和cursor.next()做业务逻辑之前,在获取mongo游标之前,调用FindIterable对象的noCursorTimeout(true)方法。例如:

FindIterable<Document> findIterable = sentenceColl.find(condition);
// set no timeout
findIterable.noCursorTimeout(true);
MongoCursor<Document> mongoCursor = findIterable.iterator();

while (mongoCursor.hasNext()) {
    mongoCursor.next();
}

答案 3 :(得分:0)

试试这个:

Iterator<BasicDBObject> it = null;
it = coll.find("{"field": {$in:#}}", fieldList).with(
        new QueryModifier() {
          public void modify(DBCursor cursor) {
              cursor.setOptions(Bytes.QUERYOPTION_NOTIMEOUT);
          }
        }
    ).as(BasicDBObject.class);