Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build combined _id property of the $group in mongo aggregation using spring data?

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??

like image 409
sunnyfinger Avatar asked Nov 10 '22 23:11

sunnyfinger


1 Answers

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")
);
like image 100
chridam Avatar answered Nov 14 '22 21:11

chridam