Search code examples
javamongodbspring-data-mongodbcriteria

how to get more clean code in java with mongoDB criteria query


I am coding mongodb query in java

criteria.andOperator(Criteria.where("id").is(id),
         Criteria.where("name").is(name),
         Criteria.where("age").is(age),
         Criteria.where("address").is(address),
         Criteria.where("phonemun").is(phonenum));

I am coding the query as above.

criteria.andOperator(Criteria.where("id").is(id),
             Criteria.where("name").is(name));
if(age != null){
  criteria.andOperator(Criteria.where("age").is(age));
}
if(address != null){
  criteria.andOperator(Criteria.where("address").is(address));
}
if(phoneNum != null){
  criteria.andOperator(Criteria.where("phonenum").is(phoneNum));
}

This is the only method that comes to mind, but the more conditions, the more messy the code becomes. Is there a better way?


Solution

  • You can try this:

    Map<String, Object> params = new HashMap<>();
    params.put("id", id);
    params.put("name", name);
    params.put("age", value);    // value is Integer or null
    // ...similarly for phoneNum, address, etc
    
    Collection<Criteria> criterias = new ArrayList<>();
    
    params.forEach((k, v) -> {
        if (v != null) {
            criterias.add(Criteria.where(k).is(v));
        }
    });
    
    Criteria criteria = new Criteria().andOperator(criterias);