使用Spring Data MongoDB进行组聚合 [英] Group aggregation using spring data mongodb
问题描述
我试图使用日期对象中的年份值作为键来编写组聚合查询,但是由于某种原因,我遇到了此异常.
I tried to write a group aggregation query using the year value from a date object as a key, but for some reason I'm getting this exception.
org.springframework.data.mapping.PropertyReferenceException: No property year(invoiceDate)
这是我要复制的mongo查询:
Here is the mongo query which I'm trying to replicate:
db.collection.aggregate([
{
$match:
{
"status": "Active"
}
},
{
$group:
{
"_id":{$year:"$invoiceDate"}
}
},
{
$sort:
{
"_id" : -1
}
}
])
这是我的Java实现:
And this is my Java implementation:
Aggregation aggregation = Aggregation.newAggregation(
match(new Criteria().andOperator(criteria())),
Aggregation.group("year(invoiceDate)")
).withOptions(newAggregationOptions().allowDiskUse(true).build());
我也没有找到对分组结果进行排序的方法.
I also didn't find a way how I can apply the sorting on the results from the grouping.
推荐答案
You're basically looking for extractYear()
which maps to the $year
operator with MongoDB:
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(new Criteria().andOperator(criteria())),
Aggregation.project().and("invoiceDate").extractYear().as("_id"),
Aggregation.group("_id"),
Aggregation.sort(Sort.Direction.DESC, "_id)
)
这通常需要进入 $project
为了使助手们高兴.
This generally needs to go into a $project
in order to make the helpers happy.
如果您确实要在 $group
然后您可以添加一个自定义操作表达式:
If you really want the expression within the $group
then you can add a custom operation expression:
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(new Criteria().andOperator(criteria())),
new AggregationOperation() {
@Override
public Document toDocument(AggregationOperationContext aggregationOperationContext) {
return new Document("$group",
new Document("_id", new Document("$year","$invoiceDate") )
);
}
},
Aggregation.sort(Sort.Direction.DESC, "_id)
)
这篇关于使用Spring Data MongoDB进行组聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!