Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data MongoDB AND/OR query with multiple optional parameters

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?

like image 675
Alexio Cassani Avatar asked Jul 30 '14 21:07

Alexio Cassani


1 Answers

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.

like image 56
Konstantin Yovkov Avatar answered Sep 23 '22 02:09

Konstantin Yovkov