IsaacLevon
IsaacLevon

Reputation: 2570

How to build a complex MongoDB query?

I have a quite large MongoDB document consisting various of fields.

I need to supply the client all the documents after applying the given filters. A filter can be firstName == name but it can also be jobType in {PROGRAMMER, DESIGNER}

Currently, I'm checking if the filter != null and if so I'm applying query.addCriteria(...)

Is there a more concise way doing it?

Upvotes: 1

Views: 100

Answers (1)

Yadhukrishna
Yadhukrishna

Reputation: 842

Yes, this looks like an ideal use case for strategy pattern. Basically, you create an interface FilterCriterion and implement it for each possible fields you want to add the filter on.

Example:

public interface FilterCriterion{

Boolean isApplicable(DummyObject dummyObject);
Criteria getCriteria(DummyObject dummyObject);

}
public class NameFilter implements FilterCriterion{

@Override
public boolean isApplicable(DummyObject dummyObject){
    return Objects.nonNull(dummyObject.firstName);
}

@Override
public Criteria getCriteria(DummyObject dummyObject){
    return Criteria.where("firstName").is(dummyObject.firstName);
}

}

Autowiring the interface will give a list of implementation beans, in that service you can collect the criteria with

Criteria criteria = new Criteria();
criteria.andOperator(criteria1, criteria2...);

Upvotes: 1

Related Questions