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

使用Spring MongoDB Java Driver构建BSON过滤器筛选未删除记录

问题分析与解决

核心错误点

  • 过滤器逻辑错误:原代码中exists("isDeleted")会匹配所有包含isDeleted字段的文档,包括值为true的已删除记录,完全违背了筛选未删除记录的需求。
  • 查询结果范围错误:调用first()仅返回第一条匹配记录,无法获取所有符合条件的结果。
  • 排序字段不匹配:排序使用的printerType与数据中的实际字段名printer_Type不一致,导致排序失效。

修正后的代码

Bson projectionFields = Projections.fields(
        Projections.include("printerTypeName"),
        Projections.excludeId());

// 构建正确的过滤器:匹配指定manufacture_Id和printer_Type,且未被删除(isDeleted不存在或为false)
Bson filter = Filters.and(
        Filters.eq("manufacture_Id", manufactureId),
        Filters.eq("printer_Type", ConfigurationTypes.PRINTER_TYPES),
        Filters.or(
                Filters.not(Filters.exists("isDeleted")),
                Filters.eq("isDeleted", Boolean.FALSE)
        )
);

// 获取所有匹配结果,修正排序字段
List<Document> docs = collection.find(filter)
        .projection(projectionFields)
        .sort(Sorts.descending("printer_Type"))
        .into(new ArrayList<>());

if (docs.isEmpty()) {
    System.out.println("No results found for printer Type Name");
    return null;
} else {
    // 打印所有符合条件的printerTypeName
    docs.forEach(doc -> System.out.println(doc.getString("printerTypeName")));
    // 若需返回单个结果,保留原逻辑返回第一条;若需返回全部,可调整返回类型为List<String>
    return docs.get(0).getString("printerTypeName");
}

验证结果

当manufacture_Id为XEROX且printer_Type匹配对应值时,会输出预期结果:

Home Jet
Home Jet 1
Home Jet 4

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 20:07:04