MongoDB Java 驱动程序 - 如何在聚合查询中禁用光标超时?

Sav*_*vas 3 java mongodb

我正在尝试使用 Mongo Java Driver 3.0.4 在大集合上运行聚合。在我收藏的小样本上,一切都很好,但是当我尝试在整个收藏中执行它时,我最终得到了MongoCursorNotFoundException. 我发现这是 Cursor 的问题,它超时并被服务器关闭。

但是,我无法理解如何设置此选项。该aggregate() 函数返回一个AggregateIterable,它只有useCursor看起来有点相关的方法。另一方面, find() 函数返回FindIterable,它有一个方便的noCursorTimeout(Boolean)方法。我不明白为什么它在 find 上如此简单,但是这个选项在聚合上没有明显的方法。我应该如何确保 Cursor 在一段时间后不会失败?

到目前为止,我的代码是这样的。

AggregateIterable<Document> iterable = db.getCollection("tweets").aggregate(asList( new Document("$sort", new Document("timestamp_ms", 1)),
        new Document("$group", new Document("_id", "$relatedTrend")
                            .append("count", new Document("$sum", 1))
                            .append("tweets", new Document("$push", new Document("timestamp_millis", "$timestamp_ms")))))).allowDiskUse(true);

iterable.forEach(new Block<Document>() {
    @Override
    public void apply(final Document document) {
    //parse field "tweets" of document and do a lot of calculations.
    }
});
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 5

检查此 MongoDB JIRA票证。您可以在启动mongodor实例时增加空闲游标超时时间mongos

mongod --setParameter cursorTimeoutMillis=<num>
Run Code Online (Sandbox Code Playgroud)

或者

mongos --setParameter cursorTimeoutMillis=<num>
Run Code Online (Sandbox Code Playgroud)

如果这不是一个选项,您还可以运行以下 shell 命令:

use admin
db.runCommand({setParameter:1, cursorTimeoutMillis: <num>})
Run Code Online (Sandbox Code Playgroud)