需求:
查询一张表,根据某字段去重后返回指定信息,支持分页,排序。
逻辑:
1,match查询符合条件的数据
2,利用分组进行去重
3,返回全部字段信息
4,排序
5,分页
mongodb原生语句实现
方法1 返回指定字段

db.getCollection('表名').aggregate([
  {
  "$match" : {"failure":{$in:["具体失效文件"]}} //查询数组类型字段,根据需求可更改
  },
  {
  "$group" : {
  "_id": { "lawId": "$lawId" }, //需要去重的字段
  "id":{"$first" :"$_id"},
  "lawId": {"$first" :"$lawId"},
  "date":{"$first" :"$date"}
  }
  },
  {
  "$project": { //设置返回字段,建立在group基础上
  "_id": 1,
  "id":1,
  "lawId": 1,
  "date":1
  }
  },
  {"$sort": {"date":-1}}, //排序
  { "$skip":0 }, { "$limit":10 } //分页
  ])

注意:表红色的为错误代码,加上的话,查询不出来

 

优化后:

db.getCollection('表名').aggregate([
    {
       "$match": {
            "createUserId": "1069"
        } //查询数组类型字段,根据需求可更改
    },
    {
        "$group": {
            "_id": "$entityId",
            "type": {
                "$first": "$type"
            },
            "entityId": {
                "$first": "$entityId"
            },
            "entityName": {
                "$first": "$entityName"
            },
            "createTime": {
                "$first": "$createTime"
            },
            "fileSize": {
                "$first": "$fileSize"
            }
        }
    },
    {
        "$sort": {
            "createTime":  - 1
        }
    }, //排序
    {
        "$skip": 0
    },
    {
        "$limit": 10
    } //分页
])

方法2 返回全部字段

db.getCollection('表名').aggregate([
  {
  "$match" : {"failure":{$in:["具体失效文件"]}} //查询数组类型字段,根据需求可更改
  },
  {
  "$group" : {
  "_id": { "lawId": "$lawId" }, //需要去重的字段
  "data":{"$first" :"$$ROOT"} //返回全部字段
  }
  },
  {
  "$project": {
  "data":1, //返回全部字段
  }
  },
  {"$sort": {"data.dae":-1}}, //根据date.dae字段排序
  { "$skip":0 }, { "$limit":10 } //分页
  ])

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.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"}]