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

Mar*_*hev 26 java spring mongodb

我有以下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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我试图实现一个MongoRepository查询,查找Question包含标签列表的所有s.我尝试过以下方法:

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

但这只适用于List我传递给方法的标签完全匹配分配给Mongo中问题的标签列表.例如,如果我在Mongo中有一个带有标签列表的问题,[ "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);
}
Run Code Online (Sandbox Code Playgroud)

但是我war根本无法部署到我的servlet容器中.(在这种情况下我得到以下错误:

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.
Run Code Online (Sandbox Code Playgroud)

您能否建议如何实现该自定义查询?

Mar*_*hev 45

我将回答我自己的问题,因为我自己找到了答案.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);
}
Run Code Online (Sandbox Code Playgroud)

  • 很好的发现.关键字必须在方法名称的末尾吗?谢谢 (2认同)
  • 得到它了!!@Query(“ {tags:{$ exists:true},$ where:'this.tags.length&gt; 0'}”)) (2认同)

ale*_*ria 9

也可以使用CONTAINING关键字:

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

示例以及它的mongo查询如何:

findByAddressesContaining(Address address)

{"addresses" : { "$in" : address}}
Run Code Online (Sandbox Code Playgroud)

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

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