java使用mongoTemplate去重排序查詢


import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
第一種,使用mongoTemplate.findDistinct去重,不支持排序,即使你的query條件帶sort排序方法。mongoTemplate.findDistinct去重,會使排序失效。
優點:查詢效率高
缺點:只返回單一字段。不可多字段返回。不能使用排序,不推薦使用
Query query = new Query();
query.addCriteria(Criteria.where("deviceId").is(getListParam.getDeviceId())).with(Sort.by(Sort.Order.desc("startDate")));
List<RedPacketDeviceRelation> list = mongoTemplate.find(query, RedPacketDeviceRelation.class);
List<String> activeCodes = mongoTemplate.findDistinct(query, "activeCode", "redPacketDeviceRelation",RedPacketDeviceRelation.class, RedPacketDeviceRelation.class);
第二種,使用mongoTemplate.aggregate去重,支持排序。推薦使用
優點:可指定返回類型。支持排序
缺點:排序是查詢效率會變的非常低
TypedAggregation tagg = TypedAggregation.newAggregation(RedPacketDeviceRelation.class,
         Arrays.asList(
//篩選條件
TypedAggregation.match(Criteria.where("deviceId").is(getListParam.getDeviceId())),
//分組過濾條件,first,as里最后包含展示的字段
TypedAggregation.group("activeCode").first("activeCode").as("activeCode").first("startDate").as("startDate"),
//挑選需要字段
          TypedAggregation.project("activeCode", "startDate"),
//排序字段
TypedAggregation.sort(Sort.by(Sort.Order.desc("startDate")))
         )
);
AggregationResults result111 = mongoTemplate.aggregate(tagg, RedPacketDeviceRelation.class);
List<RedPacketDeviceRelation> rd = result111.getMappedResults();
log.debug("排序后的mongoTemplate.group列表1:"+rd);

第三種,用法和第二種類似
Aggregation agg = Aggregation.newAggregation(
// 挑選所需的字段,類似select *,*所代表的字段內容
Aggregation.project("activeCode", "startDate","packetType"),
// sql where 語句篩選符合條件的記錄
Aggregation.match(Criteria.where("deviceId").is(getListParam.getDeviceId())),
// 分組條件,設置分組字段
Aggregation.group("activeCode").first("activeCode").as("activeCode").first("startDate").as("startDate"),
// 排序(根據某字段排序 倒序)
Aggregation.sort(Sort.Direction.DESC,"startDate"),
// 重新挑選字段
Aggregation.project("activeCode")
);
AggregationResults<JSONObject> results = mongoTemplate.aggregate(agg, "redPacketDeviceRelation", JSONObject.class);
List<JSONObject> a= results.getMappedResults();
log.debug("排序后的code列表2:[{}]",results);

原創文章,引用注明出處:https://www.cnblogs.com/guangxiang/p/12366017.html



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM