Spring-Mongo $ne support : How to use $ne in find by field methods?

Issue

I have a mongo collection model in Spring-boot as follows

@Document
class MyModel{
       @Id
       String id;
       String name;
}

I created its repository

public interface MyModelRepository extends MongoRepository<MyModel,String> {

}

I know I can declare a method inside MyModelRepository to find documents having a name value equal to some name (let John) using findByField(String name). But if I want all documents that name is not equal to John then I am not sure how can I declare this method in same repository.

I know I can use @Query or Criteria with MongoTemplate but I am wondering is it possible without @Query or criteria just like findBy equal value. I tried List<MyModel> findByNotEqualName(String name) and List<MyModel> findByNotName(String name) But both are throwing error. I tried to search it but did not found anything, Found this but answer to this question also using Criteria with MongoTemplate.

Solution

NOT ($ne) operator is suppose to be after field name. so correct syntax will be

public interface MyModelRepository extends MongoRepository<MyModel,String> {
         List<MyModel> findByNameNot(String name);
}

Answered By – MADHAVI KUMARI

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published