5

我在 mongodb 文档中找到了这个 mongo 命令:

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 } 
        } 
      } 
   ] 
) 

使用spring数据的聚合时,很容易将一个文档属性绑定到$group中的_id,调用Aggregation.group(Feild ...)

但是对于上述情况,_id 属性被组合在一起,我无法用 Java 构建它。大家有什么解决办法???我的意思是如何用Java表达上面的js??

非常感谢...

@update..... $group 的 _id 使用像 $month $dayOfMonth 这样的 mongo 函数......我怎样才能在 Spring 数据中做到这一点?

4

1 回答 1

1

您可以尝试先在投影操作中使用SpELandExpression来投影字段,然后在组操作中按新字段进行分组:

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")
);
于 2015-11-04T14:52:16.380 回答