7

I'm trying to execute a query with more than 2 optional parameters but I don't get any result. For the 2 parameters I followed the answer of this question spring-data-mongo - optional query parameters?.

So for example, with the following query everything is ok:

@Query("{$and: [{$or : [ { $where: '?0 == null' } , { a : ?0 } ]}, {$or : [ { $where: '?1 == null' } , { b : ?1 }]}]}")

But if I add one more parameter it stops to work:

@Query("{ $and : [{$and: [{$or : [ { $where: '?0 == null' } , { a : ?0 } ]}, {$or : [ { $where: '?1 == null' } , { b : ?1 }]}]},{$or : [ { $where: '?2 == null' } , { c : ?2 }]}]}")

I triple checked the syntax and seems ok, but I get empty results (even if I'm sure I should obtain at least few documents).

Any idea?

1 Answer 1

8

If you try carefully hand-format you query to be more readable, you will note that you have made a few mistakes with the closing brackets.

Try this query instead:

{ $and : 
    [{
       $and: 
        [
         {$or : [ { $where: '?0 == null' } , { a : ?0 }]}, 
         {$or : [ { $where: '?1 == null' } , { b : ?1 }]},
         {$or : [ { $where: '?2 == null' } , { c : ?2 }]}
        ]
    }]
}

Side note: I think one $and will be enough, i.e. remove the top-level $and operator.

Sign up to request clarification or add additional context in comments.

2 Comments

Thk! I didn't know $and operator could work with more than 2 elements. It works and it is more readable too :-)
Is there a way to use $regex here ? Because I couldn't make it work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.