Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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);
over 4 years ago · Santiago Trujillo Report

0

If you had a method like addCriteria (Criteria crit, String fieldName, Object val)

if (val != null) {
    criteria.andOperator(Criteria.where(fieldName).is(val));
}

then you could put the logic in this method

addCriteria (criteria, "Age", age);
addCriteria (criteria, "Name", name);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!