How to build a joint _id property of 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 aggregation, it is easy to bind one Document property to _id in $ group with a call in Aggregation.group (Feild ...)

but for the above situation, the _id property is combined, and I could not create it in Java. Do you guys have any solution ??? I mean how to express js above in Java ??

many thanks...

@update ..... _id of $ group uses mongo functions like $ month $ dayOfMonth ... How to do this in spring data?

+4
source share
1 answer

, SpEL andExpression , :

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")
);
0

All Articles