例如,我有Java对象:
public class Foo {
private Example example;
}
public class Example {
private String str1;
private String str2;
}
字段示例可以为null。
我需要获取str1包含例如“ text”的所有Foo对象。根据文档,我尝试过:
@Query(value = "{ 'example' : { $exists : true, $elemMatch : { str1 : { $regex: '.*?0.*'} } } }")
但它返回空页面。
在存储库中定义查询:
@Repository
public interface FooRepo extends MongoRepository<Foo, String> {
@Query("{ 'example' : { $exists : true }, 'example.str1' : { $regex: ?0 } }")
List<Foo> findByExamplePropertyRegex(String regexStr);
}
样本中foo
收集的四个文档:
{ "example" : { "str1" : "apple", "str2" : "rose" } },
{ "example" : { "str1" : "pineapple", "str2" : "jasmine" } },
{ "other": "stuff" },
{ "example" : null }
使用CommandLineRunner
以下命令从Spring Boot应用程序运行查询:
@Autowired
private FooRepo repo;
// ...
public void run(String... strings) throws Exception {
String regexStr = "apple"; // -or- "in"
List<Foo> list = repo.findByExamplePropertyRegex(regexStr);
list.forEach(System.out::println);
输出将是带有regexStr
“苹果”的两个文档,以及带有输入“ in”的一个文档。
另请参见:$ regex运算符。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句