2

Firstly, the document schema am querying on, is as follows:

{x:10, y:"temp", z:20} 

There are multiple other documents in the collection with the same schema as above.

Now, I have a list where each element contains, pair of values belonging to keys x and y. This can be pictured as:

       [{10,"temp"}, {20,"temp1"}, .....] 
keys ->  x    y        x    y

Now, am aware, that if I process the array in a loop and take each pair, I can construct a query like:

query.addCriteria(Criteria.where("x").is(10).and("y").is("temp"))

This will return the document if it matches the AND criteria. I can query with all the pairs in the list in such a manner. But this approach will involve a high number of calls to the data base since for each pair in the list, there is a database call.

To avoid this, Is there any way I can query for all the documents that match this AND criteria for each element in the list, in a single call, using spring data MongoDb Api? Framed differently, I want to avoid looping through the array and making multiple calls, if possible.

1 Answer 1

5

You could use Criteria.orOperator to return each Document that match at least one Criteria of your list.

Build your list of Criteria looping over your list

List<Criteria> criteriaList = new ArrayList<>();
for (item : yourList) {
  criteriaList.add(Criteria.where("x").is(item.x).and("y").is(item.y));
}

Build your query using orOperator:

Query.query(new Criteria.orOperator(criteriaList.toArray(new Criteria[criteriaList.size()])));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.