【问题标题】:How to build combined _id property of the $group in mongo aggregation using spring data?如何使用spring数据在mongo聚合中构建$group的组合_id属性?
【发布时间】:2015-01-02 10:04:20
【问题描述】:

我在 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 data的Aggregation时,很容易通过调用Aggregation.group(Feild ...)将一个Document属性绑定到$group中的_id

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

非常感谢...

@更新..... $group 的 _id 使用 $month $dayOfMonth 之类的 mongo 函数...如何在 Spring 数据中执行此操作??

【问题讨论】:

  • $group 的 _id 使用了 $month $dayOfMonth 之类的 mongo 函数...我如何在 Spring 数据中做到这一点??
  • 在这里对你有感觉。我最初确实认为这是重复的,但它肯定不是。 Spring-Mongo 似乎缺乏使_id 的这些部分用于分组的必要操作。我唯一能清楚地看到的是单独的$project 操作,这不是最佳的,也没有当前的optimizer coalescence 发生帮助。适当地重新标记,以便希望像 Oliver 这样的人能够对此有所了解。

标签: java mongodb mongodb-query aggregation-framework spring-mongo


【解决方案1】:

您可以尝试先在投影操作中使用 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")
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多