问题
E.g. I have Java objects:
public class Foo {
private Example example;
}
public class Example {
private String str1;
private String str2;
}
Field example can be null.
I need to get all Foo objects where str1 contains e.g. "text". According to documentation I tried:
@Query(value = "{ 'example' : { $exists : true, $elemMatch : { str1 : { $regex: '.*?0.*'} } } }")
but it returns empty Page.
回答1:
Define the query in the repository:
@Repository
public interface FooRepo extends MongoRepository<Foo, String> {
@Query("{ 'example' : { $exists : true }, 'example.str1' : { $regex: ?0 } }")
List<Foo> findByExamplePropertyRegex(String regexStr);
}
Sample four documents in foo
collection:
{ "example" : { "str1" : "apple", "str2" : "rose" } },
{ "example" : { "str1" : "pineapple", "str2" : "jasmine" } },
{ "other": "stuff" },
{ "example" : null }
Run the query from Spring Boot application using CommandLineRunner
:
@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);
The output will be two documents with the regexStr
is "apple", and one document with input "in".
Also, see: $regex operator.
来源:https://stackoverflow.com/questions/61099144/mongodb-query-with-exists-and-elemmatch-doesnt-work