Afsar Ahamad
Afsar Ahamad

Reputation: 1997

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

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.

Upvotes: 1

Views: 800

Answers (1)

MADHAVI KUMARI
MADHAVI KUMARI

Reputation: 719

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

Upvotes: 1

Related Questions