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

Spring Boot MongoDB Repository自定义查询方法大小写匹配异常问题

问题根源

MongoDB默认的字符串查询是区分大小写的,Spring Data自动生成的findByFirstname方法会严格匹配大小写,所以只有数据库中存全小写subham时能查到结果,Subham或SUBHAM会因为大小写不匹配被过滤。

解决方法

方法1:使用Spring Data内置的忽略大小写命名规则

直接修改方法名,Spring Data支持通过IgnoreCase后缀自动生成不区分大小写的查询:

@Repository
public interface PatientRepository extends MongoRepository<Patient, String> {
    // 忽略大小写查询 firstName
    List<Patient> findByFirstnameIgnoreCase(String firstName);
    
    // 其他需要忽略大小写的字段同理
    List<Patient> findByLastnameIgnoreCase(String lastName);
    
    List<Patient> findByEmail(String email);
    List<Patient> findByPincode(String pincode);
    List<Patient> findByContactnumber(String contactDetails);
    List<Patient> findByCityIgnoreCase(String city);
}

方法2:手动通过@Query注解指定不区分大小写匹配

如果不想修改方法名,用MongoDB的$regex配合i选项(忽略大小写)实现:

@Repository
public interface PatientRepository extends MongoRepository<Patient, String> {
    @Query("{ 'firstname' : { $regex: ?0, $options: 'i' } }")
    List<Patient> findByFirstname(String firstName);
    
    @Query("{ 'lastname' : { $regex: ?0, $options: 'i' } }")
    List<Patient> findByLastname(String lastName);
    
    List<Patient> findByEmail(String email);
    List<Patient> findByPincode(String pincode);
    List<Patient> findByContactnumber(String contactDetails);
    @Query("{ 'city' : { $regex: ?0, $options: 'i' } }")
    List<Patient> findByCity(String city);
}

方法3:给集合设置全局不区分大小写的排序规则

如果希望整个集合的字符串查询都默认忽略大小写,先通过MongoDB Shell给集合设置collation(排序规则),指定strength:2(忽略大小写):

// 给firstname字段创建忽略大小写的索引
db.patients.createIndex({ firstname: 1 }, { collation: { locale: 'en', strength: 2 } })

// 或者修改集合的默认collation
db.runCommand({
  collMod: "patients",
  collation: { locale: 'en', strength: 2 }
})

之后在Spring Data的Repository接口上添加@Collation注解同步规则:

@Repository
@Collation("locale='en', strength=2")
public interface PatientRepository extends MongoRepository<Patient, String> {
    List<Patient> findByFirstname(String firstName);
    // 其他方法保持不变
}

内容的提问来源于stack exchange,提问作者Subham Kr Gupta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 01:15:39