带有 $exists 和 $elemMatch 的 MongoDB 查询不起作用 [英] MongoDB query with $exists and $elemMatch doesn't work
本文介绍了带有 $exists 和 $elemMatch 的 MongoDB 查询不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如我有 Java 对象:
E.g. I have Java objects:
public class Foo {
private Example example;
}
public class Example {
private String str1;
private String str2;
}
字段 example 可以为 null.
Field example can be null.
我需要获取 str1 包含的所有 Foo 对象,例如文本".根据 documentation 我试过:
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.*'} } } }")
但它返回空页面.
推荐答案
在存储库中定义查询:
@Repository
public interface FooRepo extends MongoRepository<Foo, String> {
@Query("{ 'example' : { $exists : true }, 'example.str1' : { $regex: ?0 } }")
List<Foo> findByExamplePropertyRegex(String regexStr);
}
foo
集合中的四个文档示例:
Sample four documents in foo
collection:
{ "example" : { "str1" : "apple", "str2" : "rose" } },
{ "example" : { "str1" : "pineapple", "str2" : "jasmine" } },
{ "other": "stuff" },
{ "example" : null }
使用 CommandLineRunner
从 Spring Boot 应用程序运行查询:
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);
输出将是两个文档,regexStr
是apple",一个文档的输入是in".
The output will be two documents with the regexStr
is "apple", and one document with input "in".
另见:$regex operator.
这篇关于带有 $exists 和 $elemMatch 的 MongoDB 查询不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文