You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java与MongoDB获取两列去重数据并实现分页查询?

实现方案

核心思路

通过MongoDB聚合框架实现,核心流程为先展开嵌套的data数组,再对emp_country和emp_city的组合做去重处理,最后叠加稳定排序+分页逻辑,保证返回结果无重复、分页顺序稳定。


1. MongoDB原生聚合逻辑

你可以先在数据库端直接执行以下语句验证效果,替换yourCollectionName为实际集合名即可:

db.yourCollectionName.aggregate([
  // 展开嵌套的data数组,把每个数组元素拆分为独立文档
  {$unwind: "$data"},
  // 按国家+城市组合分组,天然实现去重
  {$group: {
    _id: {
      emp_country: "$data.emp_country",
      emp_city: "$data.emp_city"
    }
  }},
  // 调整输出结构,和预期返回格式对齐
  {$project: {
    _id: 0,
    emp_country: "$_id.emp_country",
    emp_city: "$_id.emp_city"
  }},
  // 必须加稳定排序,否则多次分页查询可能出现数据错位、重复
  {$sort: {emp_country: 1, emp_city: 1}},
  // 分页逻辑:skip为偏移量,limit为每页条数,示例为第1页每页10条
  {$skip: 0},
  {$limit: 10}
])

针对你提供的样本数据,执行以上语句返回的结果和你给出的预期输出完全一致。


2. Java代码实现(基于MongoDB Java Driver 4.x)

依赖引入(Maven示例)

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>4.10.2</version>
</dependency>

核心业务代码

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Sorts;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
import static com.mongodb.client.model.Projections.*;
import static java.util.Arrays.asList;

public class DistinctAddressQuery {
    public static void main(String[] args) {
        // 替换为实际MongoDB连接地址
        try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {
            // 替换为实际数据库名、集合名
            MongoDatabase db = mongoClient.getDatabase("test_db");
            MongoCollection<Document> collection = db.getCollection("employee");

            // 分页参数示例:第1页,每页10条
            int pageNum = 1;
            int pageSize = 10;
            long skipOffset = (pageNum - 1L) * pageSize;

            // 构造聚合管道执行查询
            List<Document> result = collection.aggregate(asList(
                    Aggregates.unwind("$data"),
                    Aggregates.group(new Document("emp_country", "$data.emp_country")
                            .append("emp_city", "$data.emp_city")),
                    Aggregates.project(fields(
                            excludeId(),
                            computed("emp_country", "$_id.emp_country"),
                            computed("emp_city", "$_id.emp_city")
                    )),
                    Aggregates.sort(Sorts.ascending("emp_country", "emp_city")),
                    Aggregates.skip((int) skipOffset),
                    Aggregates.limit(pageSize)
            )).into(new ArrayList<>());

            // 打印结果
            result.forEach(System.out::println);
        }
    }
}

内容的提问来源于stack exchange,提问作者prabhakar srivastava

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 15:57:03