【问题标题】:MongoDB query with $exists and $elemMatch doesn't work带有 $exists 和 $elemMatch 的 MongoDB 查询不起作用
【发布时间】:2020-04-08 11:01:26
【问题描述】:

例如我有 Java 对象:

public class Foo {
   private Example example;
}
public class Example {
   private String str1;
   private String str2;
}

字段示例可以为空。

我需要获取 str1 包含的所有 Foo 对象,例如“文本”。根据documentation我试过了:

@Query(value = "{ 'example' : { $exists : true, $elemMatch : { str1 : { $regex: '.*?0.*'} } } }")

但它返回空页面。

【问题讨论】:

    标签: java spring mongodb mongodb-query


    【解决方案1】:

    在存储库中定义查询:

    @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 是“apple”,一个文档的输入是“in”。

    另外,请参阅:$regex operator

    【讨论】:

    • 当然我在存储库中有这个查询。不幸的是,您的查询也返回空页面。
    • 你必须解释一下。您收藏的文件有哪些?您的疑问是什么?
    • 我发布的代码是一个工作示例;它根据查询和示例文档返回值。您的两个 Java POJO 类需要完整才能使代码正常工作。这些类需要一个带有参数的构造函数、getter 和 setter 方法,以及一个重写的 toString 方法,以将结果对象值打印到控制台。请参阅此Spring Data MongoDB Repositories 文档;它还有一些创建用于查询的 POJO 类的示例。
    • 我编辑了输入错误的代码:“str-1”和“str-2”更改为“str1”。和“str2”。
    • 我的模型有构造函数、getter 等。在您回复后,我的存储库方法如下所示: @Query(value = "{ 'example' : { $exists : true, $elemMatch : { example.str1 : { $regex: ?0} } } }") Page methodName(String str1); 我想以 JSON 格式返回,但页面内容为空。对于测试,我从我的数据库中获取所有元素并在流中过滤它们以检查是否存在真正需要的项目 - 并且它们存在。我使用 MongoDB 已经有一段时间了,但我以前从未遇到过这种情况。我认为问题可能是 $exists$elemMatch 的组合。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 2020-08-14
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多