【问题标题】:Max value of a field with mongo-java-drivermongo-java-driver 字段的最大值
【发布时间】:2017-10-21 13:26:28
【问题描述】:

我想获取整个集合 4programmersdate 字段的最大值。

在 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);

结果我得到:Fri Oct 20 00:44:50 CEST 2017

first() 可能有问题吗?

【问题讨论】:

    标签: java mongodb


    【解决方案1】:

    Aggregates.group 的第一个参数应该是 null 而不是 "$date"(实际上是 _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");
    

    【讨论】:

      猜你喜欢
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      相关资源
      最近更新 更多