Spring Data MongoDB 仓库:查询多个字段

11

这是我的文件:

@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进行查询,并在它们之间加入OR?

2个回答

12

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

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
默认情况下,它是否使用正则表达式而不进行完整的文本比较? - shayy
请参阅http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongodb.repositories.queries。 - Oliver Drotbohm
太棒了!非常感谢。 - shayy

8

所以回答我的问题,这是我想出来的解决方案。如果有人知道更高效的方法,我会很感激(我认为文本搜索不适用于部分单词)。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接