这是我想要使用 Java mongodb 驱动程序运行的聚合。
db.mycollection.aggregate(
[
{
$group:
{
_id: { status: "$status" },
totalAmount: { $sum: "$filesize" }
}
}
]
)
命令在 Shell 中运行良好,针对 Mongo 3.6。
尝试在 Java 中运行时:
"errmsg" : "The 'cursor' option is required, except for aggregate with the explain argument"
我无法从 Java 文档中找出如何指定“光标”选项或文档中指定的任何选项:
https://docs.mongodb.com/manual/reference/method/db.collection.aggregate/#db.collection.aggregate
在 Java 中,聚合命令仅采用以下参数:
collection.aggregate(管道,aggregationOptions));
- 管道:列表
- aggregationOptions:应用于的选项 聚合...
聚合选项: - 输出模式 - 允许磁盘使用 - 批量大小 - 最大时间
最佳答案
写这个问题时我提出了以下解决方案:
您必须将outputMode设置为CURSOR,如下所示:
AggregationOptions aggregationOptions = AggregationOptions.builder().outputMode(AggregationOptions.OutputMode.CURSOR).build();
Iterator<DBObject> cursor = getCollection().aggregate(pipeline, aggregationOptions);
outputMode 只有两个选项:
- 光标
- 内联。
内联返回错误...
当尝试在 Shell 和 Java 之间工作时,这个接口(interface)非常困惑。
允许选项成为 DBObject 文档似乎是有意义的。或者,有一个采用 DBObject 的 AggregationOptions 构造函数。
关于Java MongoDB 3.6 带有游标选项的聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53347611/