Spring boot - 在 mongoDB 中处理 $regex 和 null



我的仓库中有以下方法:

@Query("{$and:[" +
"{$or:[{$where: '(?0) == null'} , {'unidadNegocio': {$regex: '^(?!?0$)', $options: 'i'}}]}," +
"{$or:[{$where: '(?1) == null'} , {'unidadNegocio': {$regex: '^?1$', $options: 'i'}}]},"+
"{$or:[{$where: '(?2) == null'} , {'cif_proveedor': {$regex: '^?2', $options: 'i'}}]},"+
"{$or:[{$where: '(?3) == null'} , {'referencia': ?3}]},"+
"{$or:[{$where: '(?4) == null'} , {'descripcion': {$regex: ?4, $options: 'i'}}]},"+
"{$or:[{$where: '(?5) == null'} , {'categoria.categoria': {$regex: ?5, $options: 'i'}}]}"+
"]}")
List<Articulo> findAllWithFilter(String me, String nombre_proveedor, String cif_proveedor, Integer codigo, String desc,
String categoriaArticulo);

如您所见,我需要使用regex.但是,方法属性可以为空,这会导致我收到以下错误:

"org.springframework.data.mongodb.UncategorizedMongoDbException: Query failed with error code 2 and error message '$regex has to be a string' on server localhost:27017; nested exception is com.mongodb.MongoQueryException: Query failed with error code 2 and error message '$regex has to be a string' on server localhost:27017"

我需要如果它只是 null 它会忽略它或其他东西并且不给我那个例外,我怎么能像现在这样用@Query注释来实现它?

这是一种使用某些字段进行筛选的方法,但该方法中的某些字段可能为 null,因为用户未选择筛选该值。

谢谢。

尝试使用 SpEL,有点像这样(我不能在这里测试这个,但你应该明白(:

@Query("{$and:[" +
"{$or:[{$where: '(?0) == null'} , #{ me == null ? {} : {'unidadNegocio': {$regex: '^(?!' + me + '$)', $options: 'i'}} }]}," +
"{$or:[{$where: '(?1) == null'} , #{ nombre_proveedor == null ? {} : {'unidadNegocio': {$regex: '^' + nombre_proveedor + '$', $options: 'i'}} }]},"+
"{$or:[{$where: '(?2) == null'} , #{ cif_proveedor == null ? {} : {'cif_proveedor': {$regex: '^' + cif_proveedor, $options: 'i'}} }]},"+
"{$or:[{$where: '(?3) == null'} , #{ codigo == null ? {} : {'referencia': codigo} }]},"+
"{$or:[{$where: '(?4) == null'} , #{ desc == null ? {} : {'descripcion': {$regex: desc, $options: 'i'}} }]},"+
"{$or:[{$where: '(?5) == null'} , #{ categoriaArticulo == null ? {} : {'categoria.categoria': {$regex: categoriaArticulo, $options: 'i'}} }]}"+
"]}")
List<Articulo> findAllWithFilter(String me, String nombre_proveedor, String cif_proveedor, Integer codigo, String desc,
String categoriaArticulo);

最新更新