2017-10-21 8 views
0

全収集dateフィールドの最大値を取得したいとします。4programmersmongo-java-driverを使用したフィールドの最大値

db.getCollection("4programmers").aggregate([ 
    { 
     $group: 
     { 
      _id: null, 
      max : {$max: "$date"} 
     } 
    } 
]) 

をし、それが日付ISODate("2017-10-20T17:12:37.000+02:00")で文書を返しますが、私はJavaで書くとき:

のmongoシェルでは、私は書くことができ、結果として

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()に何か問題がありますか?

答えて

1

Aggregates.groupの最初の引数は、 "$ date"(実際には_id: null)の代わりに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"); 
関連する問題