【问题标题】:Query for value or null in with Spring Data MongoDB使用 Spring Data MongoDB 查询 value 或 null
【发布时间】:2021-04-09 08:42:10
【问题描述】:

我有一个带有“oficina”和“marcaResolucion”字段的模型。我需要查询那些在'marcaResolucion'中具有指定的oficina和具有以下值的那些:“PE”、“”或null。

我尝试了以下查询,但得到的结果比预期的要多。这个查询有问题吗?

@Query("$and:" + 
       "        [" + 
       "         { oficina : ?0 }," + 
       "         { marcaResolucion: {$in: ?1} }" +
       "        ]")
List<OperacionPendiente> findByOficinaAndInMarcaResolucion(final String oficina, final List<String> marcaResolucion);

我正在使用resttemplate,如果可能的话不想更改它。

【问题讨论】:

标签: mongodb mongodb-query spring-data-mongodb


【解决方案1】:

这个变体应该可以工作:

@Query("{ oficina : ?0, marcaResolucion: {$in: ?1} }")
List<OperacionPendiente> findByOficinaAndInMarcaResolucion(String oficina, List<String> marcaResolucion);

您可以使用findByOficinaAndInMarcaResolucion2("some oficina", asList("PE", null)) 调用它。

如果您真的只想检查单个marcaResolucion,您可以使用以下方法定义:

@Query("{ oficina : ?0, marcaResolucion: {$in: [?1, null]} }")
List<OperacionPendiente> findByOficinaAndInMarcaResolucion2(String oficina, String marcaResolucion);

您可以使用findByOficinaAndInMarcaResolucion("some oficina", "PE") 调用它。

有一个working sample including tests demonstrating this on Github。

【讨论】:

    猜你喜欢
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    相关资源
    最近更新 更多