Skip to content

Instantly share code, notes, and snippets.

@japharr
Created March 6, 2017 13:24
Show Gist options
  • Save japharr/f15a871d853ff45398f7f02667000e51 to your computer and use it in GitHub Desktop.
Save japharr/f15a871d853ff45398f7f02667000e51 to your computer and use it in GitHub Desktop.
Spring Data MongoDB month aggregation
Criteria criteria = new Criteria().andOperator(
where("warehouse").is(warehouse),
where("date").gte(currentYear.getStart()),
where("date").lte(currentYear.getEnd())
);
ProjectionOperation dateProjection = project()
.and("amount").as("amount")
.and("date").extractYear().as("year")
.and("date").extractMonth().as("month");
GroupOperation groupBy = group("year", "month")
.sum("amount").as("total")
.count().as("count");
Aggregation agg = newAggregation(
match(criteria),
dateProjection,
groupBy,
sort(Sort.Direction.ASC, "year", "month")
);
//Convert the aggregation result into a List
AggregationResults<InvoiceHistory> groupResults = mongoTemplate.aggregate(agg, Invoice.class, InvoiceHistory.class);
@miterial
Copy link

miterial commented Apr 8, 2020

and what is the type of date?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment