Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用mongo java驱动程序的字段的最大值_Java_Mongodb - Fatal编程技术网

使用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");