使用mongo java驱动程序的字段的最大值
我想获取整个集合使用mongo java驱动程序的字段的最大值,java,mongodb,Java,Mongodb,我想获取整个集合4个程序的date字段的最大值 在mongo shell中,我可以写: db.getCollection("4programmers").aggregate([ { $group: { _id: null, max : {$max: "$date"} } } ]) 它返回一个日期为ISODate的文档(“2017-10-20T17:12:37.000+02:00”)
4个程序的date
字段的最大值
在mongo shell中,我可以写:
db.getCollection("4programmers").aggregate([
{
$group:
{
_id: null,
max : {$max: "$date"}
}
}
])
它返回一个日期为ISODate的文档(“2017-10-20T17:12:37.000+02:00”)
,但当我用java编写时:
Date d = collection.aggregate(
Arrays.asList(
Aggregates.group("$date", Accumulators.max("maxx", "$date"))
)
).first().getDate("maxx");
System.out.println(d);
因此,我得到:2017年10月20日星期五00:44:50 CEST
first()
可能有问题吗?聚合的第一个参数。group
应该是null而不是“$date”(它实际上是\u id:null
)。
因此,代码应该如下所示:
Date d = collection.aggregate(
Arrays.asList(
Aggregates.group(null, Accumulators.max("maxx", "$date"))
)
).first().getDate("maxx");
或者,您也可以在不使用聚合类的情况下执行相同的操作:
collection.aggregate(asList(new Document("$group", new Document("_id", null)
.append("max", new Document("$max", "$date")))))
.first().getDate("max");