Spring mongo adding criteria to and operator dynamicaly

Prashant Thorat picture Prashant Thorat · Apr 22, 2014 · Viewed 12.6k times · Source

I am trying to create dynamic query with user input with and operation My code is I created List of criteria like:

List<Criteria> criterias = new ArrayList<Criteria>();

and added criteria to this list.And its getting added successfully. now I want to make and operator between each criteria.

 Criteria criteria = new Criteria().andOperator(criterias.get(0), criterias.get(1));

It works fine But my input is not fixed so I want it should added dynamically, I tried like

for(int i=0;i<criterias.size();i++)
  Criteria criteria = new Criteria().andOperator(criterias.get(i));

where I am missing?

Answer

jmen7070 picture jmen7070 · Apr 27, 2014

To unite all criterias from a list of criterias by "$and" operator :

Criteria criteria = new Criteria().andOperator(criterias.toArray(new Criteria[criterias.size()]));

here is docs