首页 > 解决方案 > MongoDB DSL filters

问题描述

When filtering with DSL if the filters that are being passed are empty then the results are empty. Could you please give some suggestions on how to ignore URL parameters that are not set.

Example:

@Query(value ="{$and:[{'country.name':{$eq:?0}},{'providerName':{$eq:?1}}]})"

The above query is working fine and the documents are returned. But if the positional filters are null then the result is empty. How to write a query that ignores the parameters if the value is not set.

Kind Regards, Ajay

标签: springmongodbmongodb-querydsl

解决方案


在这种情况下,我强烈建议使用 Query API 来构建基于传递参数的查询,但是如果你想使用查询 DSL,可以这样做,你必须检查 null 并且可以构建相应地查询。

@Query("{$and :["
        + "?#{ [0] == null ? { $where : 'true'} : { 'country.name' : {$eq:[0]}} },"
        + "?#{ [1] == null ? { $where : 'true'} : { 'providerName' : {$eq:[1]}}}"
        + "]}")

参考:mongodb.repositories.queries.json-spel


推荐阅读