需求:
查询一张表,根据某字段去重后返回指定信息,支持分页,排序。
逻辑:
1,match查询符合条件的数据
2,利用分组进行去重
3,返回全部字段信息
4,排序
5,分页
mongodb原生语句实现
方法1 返回指定字段
db.getCollection('表名').aggregate([ 注意:表红色的为错误代码,加上的话,查询不出来
优化后: db.getCollection('表名').aggregate([ |
方法2 返回全部字段
db.getCollection('表名').aggregate([ |
java代码MongoTemplate实现方法1
public void searchListPages(ReqQyPage<DownrdListReq> req) {
if(req.getActiveUser()==null){
return ResultIf.FAIL("登录失效");
}
ResultIf<List<DowndDto>> res = null;
Criteria criteria =Criteria.where("createUserId").is(String.valueOf(req.getActiveUser().getUid()));
if (req.getData() != null) {
//模糊查询:标题
if (StringUtils.isNotEmpty(req.getData().getSearchText())) {
// 构建查询条件
criteria.and("entityName").regex(req.getData().getSearchText());
}
}
// 分组查询分组后的总记录数
Aggregation aggregation2 = Aggregation.newAggregation(
Aggregation.match(criteria), //查询条件
Aggregation.group("entityId") //分组条件
);
AggregationResults<DowndDto> aggregate2 = downloadRecordDao.aggregate(aggregation2);
int totalCount = aggregate2.getMappedResults().size();
List<DowndDto> data = null;
if(totalCount>0){
List <Sort.Order> orders = new ArrayList <Sort.Order> ();
orders.add(new Sort.Order(Sort.Direction.DESC, "createTime"));
Sort sort = Sort.by(Sort.Order.desc("createTime"));
Aggregation aggregation = Aggregation.newAggregation(
// sql where 语句筛选符合条件的记录
Aggregation.match(criteria),
// 分组条件,设置分组字段
Aggregation.group("entityId")
.first("type").as("type")
.first("entityId").as("entityId")
.first("entityName").as("entityName")
.first("createTime").as("createTime")
.first("fileSize").as("fileSize"),
// 排序(根据某字段排序 倒序)
Aggregation.sort(Sort.Direction.DESC,"createTime"),
Aggregation.skip(req.getPage() * req.getSize()),//跳到第几个开始
Aggregation.limit(req.getSize())//查出多少个数据
);
AggregationResults<DowndDto> results =
downloadRecordDao.aggregate(aggregation);
data = results.getMappedResults();
}
Pageable pageable = new Pageable((int) req.getPage(), (int) req.getSize(), totalCount);
res = ResultIf.SUCCESS(data, pageable, ResultIf.SUCCESS);
return res;
}
返回结果:
参数:[{"createTime":1627522794893,"entityId":"61068791d843fb1","entityName":"U形","fileSize":"","id":"6102067823e268791d843fb1","type":"NDARD_PARTS"},{"createTime":1627367395374,"entityId":"60fe46daa5e8b6db","entityName":"U形螺1栓","fileSize":"","id":"60fe46daaa01256e65e8b6db","type":"STAN_PARTS"}]
有不懂的地方请留言