Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data MongoDB Repositories Query multiple fields

Here is my document:

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

I'm trying to query for posts with title or description with a like operator. My Repository

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

How do i perform this query with LIKE on both fields with an or between them?

like image 389
shayy Avatar asked Oct 10 '15 16:10

shayy


1 Answers

You can even go without any explicit query declaration if needed:

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);
  }
}
like image 131
Oliver Drotbohm Avatar answered Oct 25 '22 13:10

Oliver Drotbohm