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<RedPacketDeviceRelation> 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


上一篇:Spring boot MongoDB多数据源,MongoRepository实现


下一篇:mongodb多数据源配置