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

Spring Boot中MongoDB通配符查询返回空数组问题求助

排查MongoDB查询返回空数组的方向

结合你的代码和数据库文档,以下是具体排查步骤:

1. 修复查询语句的字段路径与语法错误

你的数据库中categoryName是包含对象的数组,每个对象内部有categoryName字段,但当前查询直接对整个数组使用$regex,同时还存在语法错误:

  • 原查询多了一个多余的右括号:@Query("{'categoryName': {'$regex': ?0 }})")
  • 未正确指向数组内对象的字段路径

修改后的Repository查询语句应为:

@Repository
public interface OrderRepository extends MongoRepository<OrderDTO, String> {
    // 匹配数组内对象的categoryName字段,可选添加'i'实现大小写不敏感
    @Query("{'categoryName.categoryName': {'$regex': ?0, '$options': 'i'}}")
    List<OrderDTO> findByCategoryName(String categoryName);
}

2. 验证Category类的字段映射

检查Category类的字段是否和数据库字段正确映射:
如果Category类的字段名是categoryName,需要确保Spring Data MongoDB能正确识别数据库里的categoryName字段,建议显式添加@Field注解:

public class Category {
    @Field("categoryName")
    private String categoryName;
    // Getter、Setter
}

若未添加该注解,可能因驼峰映射规则导致字段不匹配。

3. 确认参数传递的正确性

在Service层添加日志打印传入的categoryName参数,验证是否和数据库中的值(比如示例里的"N")一致:

public List<OrderDTO> searchOrderByCategoryName(String categoryName){
    System.out.println("传入的分类名称:" + categoryName); // 打印参数
    return or.findByCategoryName(categoryName);
}

同时检查Controller的请求路径是否正确,比如请求/portal/search/N是否能正确触发接口。

4. 直接在MongoDB客户端验证查询

使用MongoDB Shell或Compass执行原生查询,确认数据库中存在匹配的记录:

db.order.find({"categoryName.categoryName": {"$regex": "N"}})

如果该查询能返回结果,说明代码层面还有问题;如果也返回空,需检查集合名是否和@Document(collection = "order")一致,或数据库中记录的categoryName值是否确实匹配参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 19:36:10