在Spring Data MongoDB中使用List参数的存储库查询

2022-09-01 05:42:26

我有以下POJO。

@Document(collection = "questions")
public class Question {

    @Id
    private String id;

    public List<String> getTags() {
        return tags;
    }

    public void setTags(List<String> tags) {
        this.tags = tags;
    }
}

我正在尝试实现一个查询,该查询查找包含标签列表的所有s。我尝试了以下方法:MongoRepositoryQuestion

@Repository
public interface QuestionRepository extends MongoRepository<Question, String> {
    List<Question> findByTags(List<String> tags);
}

但这只有在我传递给方法的标记完全匹配Mongo中分配给问题的标记列表时才有效。例如,如果我在Mongo中有一个问题,其中包含标签列表,当我传递给该方法时,它不会返回。List[ "t1", "t2", "t3" ]findByTags(List)[ "t1", "t2" ]

我也尝试了以下方法:

@Repository
public interface QuestionRepository extends MongoRepository<Question, String> {
    @Query("{ tags: { $all: ?0 } }")
    List<Question> findByTags(List<String> tags);
}

但后来我的根本无法部署到我的 servlet 容器中。(在这种情况下,我收到以下错误:war

The web application [backend] appears to have started a thread named [cluster-1-db:27017] but has failed to stop it. This is very likely to create a memory leak.

请您就如何实现该自定义查询提供建议吗?


答案 1

我会回答我自己的问题,因为我刚刚自己找到了答案。Spring Data MongoDB 文档中的以下部分列出了 Spring 用于查询派生的所有受支持的关键字:

http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#repository-query-keywords

以下实现适用于上述用例:

@Repository
public interface QuestionRepository extends MongoRepository<Question, String> {
     List<Question> findByTagsIn(List<String> tags);
}

答案 2

也可以使用包含关键字:

@Repository
public interface QuestionRepository extends MongoRepository<Question, String> {
     List<Question> findByTagsContaining(List<String> tags);
}

示例及其 mongo 查询如下所示:

findByAddressesContaining(Address address)

{"addresses" : { "$in" : address}}

这也可以接受参数中的地址列表。

请参阅文档:https://github.com/spring-projects/spring-data-mongodb/blob/e28bede416e4ddac19a35dc239388afc90b9cac4/src/main/asciidoc/reference/mongo-repositories.adoc