【问题标题】:Group aggregation using spring data mongodb使用spring数据mongodb进行组聚合
【发布时间】:2018-10-28 13:26:12
【问题描述】:

我尝试使用日期对象中的年份值作为键来编写组聚合查询,但由于某种原因,我遇到了这个异常。

org.springframework.data.mapping.PropertyReferenceException: No property year(invoiceDate)

这是我要复制的 mongo 查询:

db.collection.aggregate([
   {
     $match:
     {
       "status": "Active"
     }
   },
   {
     $group:
     {
      "_id":{$year:"$invoiceDate"}
     }
  },
  {
    $sort:
    {
      "_id" : -1
    }
  }
])

这是我的 Java 实现:

Aggregation aggregation = Aggregation.newAggregation(
    match(new Criteria().andOperator(criteria())),
    Aggregation.group("year(invoiceDate)")
).withOptions(newAggregationOptions().allowDiskUse(true).build());

我也没有找到如何将排序应用于分组结果的方法。

【问题讨论】:

  • Aggregation.sort() - 为什么要叫其他名字?
  • 我认为您需要在排序方法中提供参考,但您可能是对的。任何想法为什么 SpEL 表达式失败?
  • Aggregation.sort() 不起作用,我得到了You have to provide at least one property to sort by!
  • 对不起,这只是一个简短的评论,而我正在离开一段时间,并打算更多地作为“提示”来学习方法和发现选项。在下面添加了实际的管道翻译。
  • 您认为提供的答案中是否有某些内容无法解决您的问题?如果是这样,请对答案发表评论,以澄清究竟需要解决哪些尚未解决的问题。如果它确实回答了您提出的问题,请注意Accept your Answers您提出的问题

标签: java mongodb spring-boot spring-data-mongodb


【解决方案1】:

您基本上是在寻找 extractYear() 映射到 MongoDB 的 $year 运算符:

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 以使帮助者开心。

如果你真的想要 $group 中的表达式,那么你可以添加自定义操作表达式:

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

【讨论】:

    猜你喜欢
    • 2017-04-23
    • 2019-06-29
    • 2017-06-02
    • 2017-07-14
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    相关资源
    最近更新 更多