首页 > 解决方案 > Spring Data with MongoDB - 按可空字段查找

问题描述

我有一个 Mongo 集合,其中包含如下文件:

a: { product: 1, country: 2, stock: 1}
b: { product: 1, country: 3, stock: 3}
c: { product: 2, country: 1, stock: 1}

有时我想获取所有国家/地区的产品库存(因此我检索所有国家/地区的产品库存,然后添加它们),有时我想要特定国家/地区的库存。

是否可以制作一个单一的方法,如:

 findByProductAndCountry(Integer product, Integer country)

像这样工作:

findByProductAndCountry(1, 2) //returns document a
findByProductAndCountry(1, null) //returns documents a and b

提前致谢!

标签: spring-dataspring-data-mongodbspring-mongodbmongotemplate

解决方案


回答您的问题:不。不可能在 mongodb 中编写这样的查询,因此您无法使用单个 spring data mongodb 方法来实现。

我建议在存储库接口中为此编写一个默认方法。这样您就可以使用其他查询方法:

public interface ProductRepository extends MongoRepository<Product, String> {

    List<Product> findByProduct(int product);

    List<Product> findByProductAndCountry(int product, int country);

    default List<Product> findByProductAndNullableCountry(Integer product, Integer country) {
        if (country != null) {
            return findByProductAndCountry(product, country);
        } else {
            return findByProduct(product);
        }
    }
}

推荐阅读