banner
WilsonJ

WilsonJ

github
follow

mongoTemplate 使用管道聚合實現 根據某個條件去重

在日常業務中可能會遇到根據資料庫某個欄位進行去重,我們可以使用mongotemplate.findDistinct方法。但是使用這個方法不太好匹配其他例如 排序、分頁、獲取總數等業務。為了能更好的實現業務我們可以使用 mongo 的 管道聚合來實現。下面直接展示代碼:

條件 + 去重 + 排序 + 分頁

public void group() {
        int page = 1;  //頁碼
        int size = 4;  //頁長

        Criteria criteria = Criteria.where("num").lte(10);
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria), //過濾條件
                Aggregation.group("age") // 根據指定欄位去重
                        .first("$$ROOT").as("document"), // 保留整個文檔
                Aggregation.replaceRoot("document"), // 將保存的整個文檔對象作為輸出文檔
                Aggregation.sort(Sort.by(Sort.Direction.ASC, "num")), // 根據指定欄位排序
                Aggregation.skip((page - 1) * size), // 跳過指定的頁數
                Aggregation.limit(size)
        );
        AggregationResults<User> results = mongoTemplate.aggregate(aggregation, "user", User.class);
        List<User> userList = results.getMappedResults();
        Aggregation countAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),     // 過濾條件
                Aggregation.group("age"),  // 根據指定欄位去重
                Aggregation.count().as("total") // 計算去重後的總數
        );

        AggregationResults<org.bson.Document> countResults = mongoTemplate.aggregate(countAgg, "user", org.bson.Document.class);
        int total = 0;
        if (!countResults.getMappedResults().isEmpty()) {
            total = countResults.getMappedResults().get(0).getInteger("total");
        }

        System.out.println("查詢出來的數據");
        System.out.println("當前為第" + page + "頁");
        userList.forEach(System.out::println);
        System.out.println("總數為:" + total);
    }

實體類

public class User {
    private Integer num;
    private String name;
    private Integer age;
}

資料庫數據

image

執行結果

image

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。