Spring Data MongoDB和/或带有多个可选参数的查询

时间:2014-07-30 21:56:10

标签: java spring mongodb spring-data

我尝试使用2个以上的可选参数执行查询,但我没有得到任何结果。对于这两个参数,我遵循了这个问题的答案spring-data-mongo - optional query parameters?

例如,使用以下查询,一切正常:

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

但如果我再添加一个参数,它就会停止工作:

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

我仔细检查了语法并且似乎没问题,但我得到空的结果(即使我确定我应该至少获得少量文档)。

有什么想法吗?

1 个答案:

答案 0 :(得分:8)

如果您仔细尝试手工格式化查询以使其更具可读性,您会注意到您使用右括号犯了一些错误。

请尝试此查询:

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

附注:我认为一个$and就足够了,即删除顶级$and运算符。

相关问题