将Mongo查询写入spring数据查询以进行聚合

时间:2017-06-28 08:24:02

标签: mongodb spring-data aggregation-framework

我想使用下面的查询与spring数据mongoDB:

{
            "contactInfo": {
                "version": "00",
                "contact": "1234567890",
                "addressLine1": "Street Number 1",
                "addressLine2": "Newyork",
                "addressLine3": "US"
            },
            "name": "John Smith",
            "department": "IT",
            "skill": "Java",
            "experience": "4",
            "workStatus": "Project"
       }

我们有这样的用户数据:

Aggregation agg = newAggregation(
     sort(Sort.Direction.DESC, "contactInfo.version"),
     group("contactInfo.contact","contactInfo.version").max("contactInfo.version").as("userCurrentInfo").first("$$CURRENT").as("userAggregate"),
     project("userAggregate")
    );
    AggregationResults<UserAggregate> groupResults = mongoOperations.aggregate(agg, "userDB", UserAggregate.class);
    List<UserAggregate> result = groupResults.getMappedResults();

我正在进行如下聚合,但得到空

 {
         "userAgg" : {
            "contactInfo": {
                "version": "00",
                "contact": "1234567890",
                "addressLine1": "Street Number 1",
                "addressLine2": "Newyork",
                "addressLine3": "US"
            },
            "name": "John Smith",
            "department": "IT",
            "skill": "Java",
            "experience": "4",
            "workStatus": "Project"
         }
       }

public class UserAggregation
{
  UserAgg userAgg;
}

public class UserAgg
{
  User user;
}

有人可以帮我获取max版本的用户数据,对于spring数据mongoDB中的上述查询。 添加了UserAggregation pojo,它看起来如何,因为我的查询返回了像

这样的数据
footer {
   position:fixed;
   left:0px;
   bottom:0px;
   height:50px;
   width:100%;
   background: aliceblue;
}

1 个答案:

答案 0 :(得分:2)

您具有空值的原因是因为您的聚合响应中没有user字段。

假设您的User pojo设置正确,您可以尝试以下聚合,您可以更新您的项目以适应您的pojo层次结构,即地图("userAgg").as("userAgg.user")

 Aggregation agg = newAggregation(
   sort(Sort.Direction.DESC, "contactInfo.version"),           
   group("contactInfo.contact","contactInfo.version").
       max("contactInfo.version").as("userCurrentInfo").first("$$CURRENT").as("userAgg"),
   project().and("userAgg").as("userAgg.user")
 );

 List<UserAggregate> groupResults = mongoOperations.aggregate(agg, "userDB", UserAggregate.class).getMappedResults();

重构版本:

您可以在此处更新相关内容,例如删除UserAggregateUserAgg pojo并直接映射到User并简化聚合查询以删除max运算符,{ {1}}对密钥进行分组,仅使用contactInfo.version$first来获取已排序数据的最大版本文档。

$$ROOT