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

无需定义实体/POJO 查询MongoDB返回指定状态的实体ID列表的实现方法

解决方案

你可以直接使用MongoDB原生的Document构造查询条件和投影规则实现需求,全程不需要依赖实体类或绑定实体的API,修改后的代码如下:

List<String> getActiveLecturersIdList() {
    // 修正原代码的赋值笔误
    MongoCollection<Document> collection = mongoTemplate.getCollection("lecturers");
    // 构造服务端过滤条件:仅匹配status为ACTIVE的文档
    Document queryFilter = new Document("status", "ACTIVE");
    // 构造投影规则:仅返回_id字段,减少冗余数据传输
    Document projection = new Document("_id", 1);
    MongoCursor<Document> cursor = collection.find(queryFilter)
            .projection(projection)
            .iterator();
    ArrayList<String> listOfIDS = new ArrayList<>();
    while (cursor.hasNext()) {
        listOfIDS.add(cursor.next().getObjectId("_id").toString());
    }
    // 关闭游标避免资源泄漏
    cursor.close();
    return listOfIDS;
}

实现说明

  • 过滤逻辑完全在MongoDB服务端执行,不会返回非ACTIVE状态的文档,无需在业务层二次过滤
  • 全程使用原生MongoCollection API实现,不需要定义任何POJO实体类,也不依赖需要绑定实体的Criteria等组件
  • 投影配置仅返回_id字段,大幅降低数据传输开销,查询效率优于全字段返回后取值的原有实现
  • 补充了游标关闭逻辑,避免长连接场景下的资源泄漏问题

如果习惯使用工具类构造查询参数,也可以用MongoDB Java Driver自带的Filters、Projections工具类实现,逻辑完全一致:

import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;

List<String> getActiveLecturersIdList() {
    MongoCollection<Document> collection = mongoTemplate.getCollection("lecturers");
    MongoCursor<Document> cursor = collection.find(Filters.eq("status", "ACTIVE"))
            .projection(Projections.include("_id"))
            .iterator();
    ArrayList<String> listOfIDS = new ArrayList<>();
    while (cursor.hasNext()) {
        listOfIDS.add(cursor.next().getObjectId("_id").toString());
    }
    cursor.close();
    return listOfIDS;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:57:00