Reputation: 789
I want to get max value of date
field for whole collection 4programmers
.
In mongo shell I can write:
db.getCollection("4programmers").aggregate([
{
$group:
{
_id: null,
max : {$max: "$date"}
}
}
])
and it returns a document with the date ISODate("2017-10-20T17:12:37.000+02:00")
but when I write in java:
Date d = collection.aggregate(
Arrays.asList(
Aggregates.group("$date", Accumulators.max("maxx", "$date"))
)
).first().getDate("maxx");
System.out.println(d);
as a result I get: Fri Oct 20 00:44:50 CEST 2017
May something is wrong with first()
?
Upvotes: 1
Views: 3208
Reputation: 3955
First argument of Aggregates.group
should be null instead of "$date" (it's actually _id: null
).
So code should look like:
Date d = collection.aggregate(
Arrays.asList(
Aggregates.group(null, Accumulators.max("maxx", "$date"))
)
).first().getDate("maxx");
or you can do the same without Aggregates class:
collection.aggregate(asList(new Document("$group", new Document("_id", null)
.append("max", new Document("$max", "$date")))))
.first().getDate("max");
Upvotes: 2