'MongoDB query for equal search with $regex

I have an entity

class Data {
string name;
string city;
string street;
string phone;
string email;
}

An api has been written to find Data by each param. This is search api so if a param is provided, it will be used if not then everything has to be queried for that param.

@Query("{'name': ?0,'city': ?1,'street': ?2, 'phone': ?3,'email': ?4}")
    Page<IcePack> findDataSearchParams(String name,
                                            String city,
                                            String street,
                                            String phone,
                                            String email);

This only works when all the params are sent in the request. It wont work if any of the params are not sent because it will look for null value in the DB for that param. I want to query everything for that param if it is not requested like the way it is done in SQL. I tired to use $regex with empty string when something is not sent but regex works like a like search but I want to do equal search

anyway to do this



Solution 1:[1]

Filtering out parts of the query depending on the input value is not directly supported. Nevertheless it can be done using @Query the $and and operator and a bit of SpEL.

interface Repo extends CrudRepository<IcePack,...> {

  @Query("""
         { $and : [ 
            ?#{T(com.example.Repo.QueryUtil).ifPresent([0], 'name')}, 
            ?#{T(com.example.Repo.QueryUtil).ifPresent([1], 'city')},
            ... 
         ]}
         """)
  Page<IcePack> findDataSearchParams(String name, String city, ...)

  class QueryUtil {
    public static Document ifPresent(Object value, String property) {
      if(value == null) {
        return new Document("$expr", true); // always true
      }
      return new Document(property, value); // eq match
    }
  }

  // ...
}

Instead of addressing the target function via the T(...) Type expression writing an EvaluationContextExtension (see: json spel for details) allows to get rid of repeating the type name over and over again.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Christoph Strobl