How to control the filters of a persistent query in mongodb

1

I have this query in my api:

@Query("{$and: ["
            + "{'online': ?5}, "
            + "{'locations.appointmentTimeRanges.weekday': ?6}, "
            + "{'specialties.name': ?7}, "
            + "{'healthInsurances.name' : ?8}"
        + "]}")

I need that when passing the parameters, when it does not come some filled field should disregard certain filter.

Example: Only online and weekday came as a parameter, as it is also looking for specialties.name and healthInsurances.name as being empty and does not find anything.

I want it at both times it looks for all the attributes together or for some sent by the client, ignoring the filter in which the parameter did not come populated. As in my example did not come specialties.name and healthInsurances.name I want to ignore them in the search.

I hope you understood my question.

    
asked by anonymous 22.08.2018 / 14:40

1 answer

0

I solved it this way:

 @Query("{$and: ["
        +"{'online': ?0}, " 
        +"{'locations.appointmentTimeRanges.weekday': { '$regex': ?1 }}, "
        +"{$or : [{'specialties.name': { '$regex': ?2, $options: 'i'}}, $where: '?4' }]}, " 
        +"{$or : [{'healthInsurances.name' : { '$regex': ?3, $options: 'i'}}, { $where: '?5' }]} "     
    + "]}")

The secret is to use $ or: and $ where, in the $ where I pass a Boolean value, if true it will consider the filter of that field, if false it will ignore. So the values? 4 and? 5 are boolean I passed by parameter only by checking if specialties.name and healthInsurances.name are different from null, if yes consider them in the filter, if not remove from the filter.

    
23.08.2018 / 15:42