Spring Data MongoDB存储库查询多个字段

时间:2015-10-10 16:12:06

标签: spring mongodb spring-data spring-data-mongodb

这是我的文件:

@Document(collection = "posts")
public class Post {
    @Id
    String id;
    String title;
    String description;
}

我尝试使用like运算符查询带有标题或说明的帖子。 我的存储库

public class PostsRepository extends MongoRepository<Post, String> {
    @Query(value = "{ $or: [ { 'title' : ?0 }, { 'description' : ?0 } ] }")
    Page<Post> queryByTitleOrDescription(String query, Pageable pageable);
}

如何在两个带有或在它们之间的字段上使用LIKE执行此查询?

2 个答案:

答案 0 :(得分:11)

如果需要,您甚至可以不使用任何明确的查询声明:

interface PostRepository extends Repository<Post, String> {

  // A default query method needs parameters per criteria

  Page<Post> findByTitleLikeOrDescriptionLike(String title, 
                                              String description,
                                              Pageable pageable);

  // With a Java 8 default method you can lipstick the parameter binding 
  // to accept a single parameter only

  default Page<Post> findByTitleOrDescription(String candidate, Pageable pageable) {
    return findByTitleLikeOrDescriptionLike(candidate, candidate, pageable);
  }
}

答案 1 :(得分:7)

所以回答我自己的问题,这是我提出的解决方案,如果有人知道更高效的东西,我会感激它(我相信文字搜索不适用,因为它不起作用部分的话)

@Query(value = "{ $or: [ { 'title' : {$regex:?0,$options:'i'} }, { 'description' : {$regex:?0,$options:'i'} } ] }")
    Page<Post> query(String query, Pageable page);
}