Collection

时间:2015-05-15 00:25:03

标签: mongodb spring-data spring-data-mongodb mongodb-java

我有一个用例,我的查询需要根据3个可选字段查找,其中一个作为集合传入。

" 3个可选字段"部分已经通过这篇文章解决了 Spring Data MongoDB AND/OR query with multiple optional parameters

但是,我对收集提交的$in问题很感兴趣。

例如,在以下查询中

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

在我的情况下,字段a实际上是作为集合传入的,我需要在MongoDB中找到那些对象a$in我传入的集合。< / p>

我尝试过像这样的事情

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

然而,当我传入null集合时,我得到了NPE。

2 个答案:

答案 0 :(得分:0)

您需要测试收集长度,如下所示spring-data-mongo - optional query parameters? 您还可以摆脱顶级 $和

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

答案 1 :(得分:0)

您实际上无法使用$ in作为可选列表参数,因为未指定时它将为null且$ in accept only列表。为此,您将在可选列表参数周围添加[],然后将此列表展平:

{ $and : 
   [
    {$or : [ { $where: '?0 == null;' },
             { $where: '[].concat.apply([],[?0]).indexOf(this.a) !== -1;'}]}, 
    {$or : [ { $where: '?1 == null' } , { b : ?1 }]},
    {$or : [ { $where: '?2 == null' } , { c : ?2 }]}
   ]
}

用于mongo版本&lt; 3.4和3.4之后您可以使用includes函数代替indexOf

相关问题