需求:
查詢一張表,根據某字段去重后返回指定信息,支持分頁,排序。
邏輯:
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"}]
有不懂的地方請留言
