2016-05-31 78 views
1

我已经为我的域对象如何获得使用

private String pair; 
private String lProvider; 
private double value; 
private DateTime dateTime; 

下列方式我创建对象这

new TestMData("EUR", "ABC", 2.5454, DateTime.now().minusYears(3)); 

我婉以下架构春天的数据对应的最大聚集功能在MongoDB中值使用弹簧数据聚合使用弹簧加重来查找对应于最大值的日期和时间。

一种方法是,我使用聚合获得最大值,并使用findone方法找到该值,但我认为这不是好方法。春天的数据提供的功能,我可以字段对应的最大值

回答

1

要获得与聚合最大值对应的日期和时间,您需要在您的聚合排序步骤管道到组运算符, d。使用$first操作者获得最高的文档时,他们下令:

db.collection.aggregate([ 
    { "$sort": { "value": -1 } }, 
    { 
     "$group": { 
      "_id": null, 
      "largestValue": { "$first": "$value" }, 
      "date": { "$first": "$dateTime" } 
     } 
    } 
]) 

在Spring数据:

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*; 

Aggregation agg = newAggregation(
    sort(DESC, "value"), 
    group().first("value").as("largestValue") 
      .first("dateTime").as("date")  
); 

AggregationResults<TestMData> results = mongoTemplate.aggregate(agg, "test", TestMData.class); 
List<TestMData> testData = results.getMappedResults(); 

上面应该有find()sort()limit()组合相同的性能:

db.collection.find().sort({ "value": -1 }).limit(1) 
+0

谢谢你的答案,但我一直在寻找,如果我可以毫不排序做的,因为我已经dateandtime的基础上排序。 – user1047873