Spring Data MongoDB Repositories Query multiple fields

shayy picture shayy · Oct 10, 2015 · Viewed 13.9k times · Source

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?

Answer

Oliver Drotbohm picture Oliver Drotbohm · Oct 11, 2015

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);
  }
}