Search code examples
javamongodbspring-bootspring-mvcspring-data-mongodb

Finding all documents by optional filters


I'm using Spring Data MongoDB framework.

I have to retrieve a list of documents from a MongoDB Collection by filtering them by some parameters that can be NULL as well.

public interface myRepo extends MongoRepository<User, String> {
  List<MyDoc> getAllByParam1AndByParam2AndByParam3(String param1, String param2, String param3);
}

Is there a way to directly implement the method getAllByParam1AndByParam2AndByParam3(...) keeping in mind that the parameters given as input can be null ?

If I simply pass null it does not work as expected.
For example with: getAllByParam1AndByParam2AndByParam3("abc", "def", null) MongoDB will return a document with

Param1 = "abc"
Param2 = "def"
Param3 = null

I want it to simply ignore the third parameter in the search.

Thank you.


Solution

  • I managed to find a very simple solution by using MongoDB Template.

    Query q = new Query();
    
    if (param1 != null) {
      Criteria param1Criteria = Criteria.where("param1Key").is(param1);
      q.addCriteria(param1Criteria);
    }
    
    if (param2 != null) {
      ...
    }
    
    ...  //others parameters checks
    
    return mongoTemplate.find(q, EntityClass.class, "collectionName");