Ad

Want To Create Dynamic Mongo Query To Accept The DTO Fields

I am creating a REST service using springboot and MONGO as database. I have a StudentDTO class with the following fields :

Class StudentDTO{
 @Id
 int s_no;
 String name;
 String dept;
 int dept_no;
 String course;

//getter and setters 
}

I have some criteria on which i need to fetch the data. These criteria may vary. Below are some example : 1. Can fetch data on name, dept 2. Can fetch data on name, id 3. May want data on name, dept and course. etc

There is no fixed combination of criteria on which I can build my query. One of the solution which is not appropriate i try to write is :

Query query = new Query();

Criteria criteria = new Criteria().andOperator(
Criteria.where("id").is(Integer.parseInt(dto.getId()),
Criteria.where("name").is(dto.getName()),
Criteria.where("dept").exists(true).is(dto.getDept()),
Criteria.where("dept_no").is(dto.getDept_no()),
Criteria.where("course").is(dto.getSource()));

query.addCriteria(criteria);
List<StudentDTO> recordsList = mongoTemplate.find(query, StudentDTO.class, "student_collection");

In the above solution there is no accommodation for the scenario is any of the field is missing. To check weather attribute exist or not i tried using the below query :

 Criteria.where("id").exist(true).is(Integer.parseInt(dto.getId());

but how i can add criteria over the DTO fields.

Ad

Answer

You can use below code. Use orOperator which accepts the array of criteria. Prepare the criteria values dynamically inside if statements and add the criteria array to or criteria.

Query query = new Query();
Criteria criteria = new Criteria();
List<Criteria> orCriterias = new ArrayList<>();
if( dto.getId() != null) {    
  orCriterias.add(Criteria.where("id").is(Integer.parseInt(dto.getId())));
}
... so on for other fields
criteria.orOperator(orCriterias.toArray(new Criteria[orCriterias.size()]));
query.addCriteria(criteria);
List<StudentDTO> recordsList = mongoTemplate.find(query, StudentDTO.class, "student_collection");
Ad
source: stackoverflow.com
Ad