2016-05-31 72 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