Usman Azhar
Usman Azhar

Reputation: 864

Spring mongodb repository returns 0 entries for query on field which is of type list

I am trying to get list of users whose comments are matching specific input keyword from mongodb document collection.

My User document defintion looks like

      public class User {
        @Id
        private String id;
        private String name;
        List<String> comments; 
      }

And my Spring Repository code looks like

     @RepositoryRestResource(collectionResourceRel = "user", path = "user")
      public interface UserRepository extends 
 MongoRepository<User,String>,CustomUserRepository {


     @Query(value = "{'comments': ?0} ")
     List<User> findByComments(String username);

     List<User> findByCommentsIn(List<String> comments);

     List<User> findBycomments(String username);

When i query it from mongo shell it works fine, db.user.find({"comments": /test/}) returns the expected result .

But same is not working with Spring Data mongodb.

And i also tried using Custom Repository , to use mongo template. The code snippet is as follows Query query = new Query()

    query.addCriteria(
            Criteria.where("comments").in("/"+user+"/")             
     );     

    List<User> result =  mongoTemplate.find(query, User.class);

Upvotes: 0

Views: 1095

Answers (1)

Usman Azhar
Usman Azhar

Reputation: 864

After little more research , it works if i use $regex in my query method. @Query(value = "{'comments': {$regex:?0}}") List findByComment(String comment);

Additional, would be interested in knowing how to debug such issues.

Upvotes: 0

Related Questions