2017-10-21 41 views
0

我想獲得整個集合的最大值date字段4programmersmongo-java驅動程序的字段的最大值

在蒙戈外殼我可以這樣寫:

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()有問題嗎?

回答

1

Aggregates.group的第一個參數應該爲空而不是「$ 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"); 
相關問題