How to control filters for a query that persists in mongodb

Asked

Viewed 82 times

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 no field comes filled should disregard certain filter.

Example: It came as parameter only the online and weekday, the way it is looking also for Specialties.name and healthInsurances.name as empty and does not find anything.

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

I hope you understand my question.

  • 1

    I think the way is around here

  • 1

    Are you using some backend?

  • Wallace I’m using Java (Spring JPA)

  • tries as follows: "{'online': ? 5 || { $exists: true } }, "

  • Solved with $Where guys. {$or : [{'Specialties.name': { '$regex': ? 2, $options: 'i'}}, { $Where: '?4' }]} uses $or and it only performs the filter of that query line if '?4' is true, which is a Boolean field that I pass by parameter.

  • 1

    If you solved the problem, post the solution as the answer. No need to change the title.

Show 1 more comment

1 answer

0


I solved it that 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 $Where I pass a boolean value, if true it will consider the filter of that field, if false it will disregard. So the values ? 4 and ? 5 are booleans that have passed by parameter just checking if Specialties.name and healthInsurances.name are different from null, if yes consider them in the filter, if it does not remove from the filter.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.