我在 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 属性绑定(bind)到 $group 中的 _id
但对于上述情况,_id 属性是组合的,我在 Java 中构建它失败了。大家有什么解决办法吗???我的意思是如何用Java表达上面的js??
非常感谢...
@更新..... $group 的 _id 使用 mongo 函数,例如 $month $dayOfMonth... 我如何在 Spring 数据中执行此操作?
最佳答案
您可以先尝试使用 SpEL andExpression
投影字段在projection操作中,然后在group操作中按新字段进行分组:
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")
);
关于java - 如何使用 spring 数据在 mongo 聚合中构建 $group 的组合 _id 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26770324/