Java – how do I check that the value is equal to at least one field in the list?

I have this method:

for (String fieldName : fieldArray) {
        Query query = new Query();
        query.addCriteria(Criteria.where("data." + fieldName).is("some_constant"));
        if (mongoTemplate.find(query,DataPoint.class).size() > 0) {
            return true;
      }
}
return false;

This code looks inefficient because it accesses DB so many fieldarray sizes

Is there any way to replace it with a single query?

Solution

In my opinion, you can use public criteria or operator (criteria... Criteria)

It should be like this:

List<Criteria> criterias = new ArrayList<>();
for (String fieldName : fieldArray) {
    //Create the criterias like you want
    criterias.add(Criteria.where("data." + fieldName).is("some_constant"));
}

Query query = new Query(
    new Criteria().orOperator(
        criterias.toArray( //convert the list into an Criteria[] for the varargs parameter
            new Criteria[criterias.size()]
        )
    )
);

This will create a criteria list for generating criteria instances. If a condition is valid (or operation, a true is enough), the instance will be valid

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>