MongoDB使用Spring数据-按可为空的字段查找

我有一个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

谢谢!

XXQJING 回答:MongoDB使用Spring数据-按可为空的字段查找

回答您的问题:否。无法在mongodb中编写这样的查询,因此您无法使用单个spring数据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);
        }
    }
}
本文链接:https://www.f2er.com/3070191.html

大家都在问