MongoDB query with $exists and $elemMatch doesn't work

旧巷老猫 提交于 2021-01-29 06:11:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!