I found this mongo command in mongodb docs:
db.sales.aggregate(
[
{
$group : {
_id : { month: { $month: "$date" }, day: { $dayOfMonth: "$date" }, year: { $year: "$date" } },
totalPrice: { $sum: { $multiply: [ "$price", "$quantity" ] } },
averageQuantity: { $avg: "$quantity" },
count: { $sum: 1 }
}
}
]
)
when using spring data's Aggregation, it is easy to bind one Document property to the _id in $group with calling to Aggregation.group(Feild ...)
but for the above situation, the _id property is combined and i failed to build it in Java. Do you guys have any solution??? I mean how to express the js above in Java??
many thanks...
@update..... the _id of the $group uses mongo functions like $month $dayOfMonth... How can I do this in Spring data??
You could try projecting the fields first by using the SpEL andExpression
in the projection operation and then group by the new fields in the group operation:
Aggregation agg = newAggregation(
project()
.andExpression("year(date)").as("year")
.andExpression("month(date)").as("month")
.andExpression("dayOfMonth(date)").as("day")
.andExpression("price * quantity").as("grossPrice"),
group(fields().and("year").and("month").and("day"))
.sum("grossPrice").as("totalPrice")
.avg("quantity").as("averageQuantity")
.count().as("count")
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With