Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

836
Views
Spring data mongodb: Optional @Query parameter no longer works

After upgrading to spring data mongodb 1.10.1, I am getting errors when running queries like:

@Query("{$and :["
            + "{ $or : [ { $where: '?0 == null' } , { 'field1' : ?0 } ] },"
            + "{ $or : [ { $where: '?1 == null' } , { 'field2' : ?1 } ] },"
            + "]}")
public Page<Entity> findAll(String param1, String param2)

Checking the error I see the parameter inside the where clause is not quoted and as I result I get:

org.springframework.data.mongodb.UncategorizedMongoDbException: Query failed with error code 139 and error message 'ReferenceError: test_param_value is not defined :

I have seen a few answers here recommending this way of handling optional parameters ((spring-data-mongo - optional query parameters?)) but it no longer works and I cannot seem to find anything in the release change log.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

In case anyone else is interested, I managed to find a workaround after checking a similar ticket int the Spring Data project.

It seems the way I was checking for null parameters in the query is not a good practice. This is from a Spring developer comment: "placeholders are not designed to compose keys/values but bind parameters. Beyond that, placeholder use in quoted strings is always problematic in terms of escaping. Using SpEL should suit your needs"

So I ended up using SpEL to do the checks on parameters and it works fine. This is how it looks:

@Query("{$and :[" 
        + "?#{ [0] == null ? { $where : 'true'} : { 'field1' : [0] } },"
        + "?#{ [1] == null ? { $where : 'true'} : { 'field2' : [1] } },"
        + "]}")
public Page<Entity> findAll(String param1, String param2, Pageable pageable);
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!