You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Spring Data MongoDB按日期年份分组聚合报错及排序问题

解决Spring Data MongoDB聚合分组按日期年份报错及排序问题

你遇到的PropertyReferenceException是因为直接把year(invoiceDate)作为分组字段传给Aggregation.group()时,Spring Data会把它当作实体类的一个属性来查找,但你的实体类里显然没有这个属性——我们需要用Spring Data MongoDB提供的聚合表达式API来对应MongoDB原生的$year操作符,而不是直接写字符串。

正确实现步骤

1. 用聚合表达式实现按年份分组

替代直接传字符串"year(invoiceDate)",我们需要用Aggregation.year("invoiceDate")来构建分组的_id,这会对应MongoDB原生的{$year:"$invoiceDate"}逻辑。

2. 添加排序操作

要对分组后的结果按年份降序排序,只需添加Aggregation.sort(Sort.Direction.DESC, "_id"),因为分组后的_id就是我们按年份生成的键。

完整Java代码实现

// 构建match条件
MatchOperation matchOperation = Aggregation.match(new Criteria().andOperator(criteria()));

// 按invoiceDate的年份分组,对应原生的{$group: {_id: {$year: "$invoiceDate"}}}
GroupOperation groupByYear = Aggregation.group(Aggregation.year("invoiceDate").as("_id"));

// 按分组后的_id(年份)降序排序,对应原生的{$sort: {_id: -1}}
SortOperation sortOperation = Aggregation.sort(Sort.Direction.DESC, "_id");

// 整合所有聚合操作并配置磁盘使用选项
Aggregation aggregation = Aggregation.newAggregation(
        matchOperation,
        groupByYear,
        sortOperation
).withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build());

对应原生MongoDB查询的映射关系

  • Aggregation.match(...) → 原生的$match阶段
  • Aggregation.group(Aggregation.year("invoiceDate").as("_id")) → 原生的{$group: {_id: {$year: "$invoiceDate"}}}
  • Aggregation.sort(...) → 原生的$sort阶段

这样修改后,既解决了属性引用异常,又实现了你想要的按年份分组+降序排序的逻辑。

内容的提问来源于stack exchange,提问作者user134

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:20:50