java - 在 Spring Data Mongodb 中使用 $$ROOT 来检索整个文档

标签 java mongodb spring-data aggregation-framework

使用 mongodb shell,我能够执行检索整个文档的聚合查询。 为此,我使用 $$ROOT 变量。

db.reservations.aggregate([
   { $match : { hotelCode : "0360" } },
   { $sort : { confirmationNumber : -1 , timestamp: -1 } },
   { $group : {
       _id : "$confirmationNumber",
       timestamp :{$first : "$timestamp"},
       fullDocument :{$first : "$$ROOT"}
   }}
])

它检索内容为confirmationNumber、timestamp、fullDocument的对象。 fullDocument 是整个文档。

我想知道是否可以使用 Spring-Data 和聚合框架做同样的事情。

我的java代码是:

TypedAggregation<ReservationImage> aggregation = newAggregation(
   ReservationImage.class,
   match(where("hotelCode").is(hotelCode)),
   sort(Direction.DESC,"confirmationNumber","timestamp"),
   group("confirmationNumber").
     first("timestamp").as("timestamp").
     first("$$ROOT").as("reservationImage"));
  List<myClass> items = mongoTemplate.aggregate(
    aggregation, 
    myClass.class).getMappedResults();

错误是: org.springframework.data.mapping.PropertyReferenceException:找不到 myClass 类型的属性 $$

你有什么想法吗?

谢谢。

最佳答案

我们创建了https://jira.spring.io/browse/DATAMONGO-954跟踪对从 MongoDB Pipeline 表达式访问系统变量的支持。

一旦到位,您应该能够编写:

Aggregation agg = newAggregation( //
   match(where("hotelCode").is("0360")), //
   sort(Direction.DESC, "confirmationNumber", "timestamp"), //
   group("confirmationNumber") //
      .first("timestamp").as("timestamp") //                
      .first(Aggregation.ROOT).as("reservationImage") //
);

关于java - 在 Spring Data Mongodb 中使用 $$ROOT 来检索整个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24185987/

相关文章:

java - 使用 Spring 数据批量插入

java - 这个错误是怎么回事? ---- token ";"上的语法错误,{ 在此 token 之后应有的内容

java - 获取 ClassCastException

java - 使用相互引用的最终成员对两个类进行子类化

java - 如何创建实用程序类?

node.js - 如何在 Mongoose 中一次插入多个文档到子文档中

c# - Mongo C# 驱动程序 : Deserialize BsonValue

java - Spring JPA + Hibernate 搜索 : How update the Search Index(Lucene) only?

java - 为什么我在查询实体时没有从 MongoOperation 获得任何结果?

node.js - 尝试在 Mongodb 中同时使用 $regex 查找多个字段