shayy
shayy

Reputation: 1312

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?

Upvotes: 11

Views: 24936

Answers (2)

Oliver Drotbohm
Oliver Drotbohm

Reputation: 83161

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

Upvotes: 12

shayy
shayy

Reputation: 1312

So to answer my own question, this is the solution I came up with, if someone knows something which is more performant I'd appreciate it (I believe text search is not applicable since it doesn't work with partial words)

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

Upvotes: 8

Related Questions