Reputation: 2195
I have a Mongo collection with documents like this:
a: { product: 1, country: 2, stock: 1}
b: { product: 1, country: 3, stock: 3}
c: { product: 2, country: 1, stock: 1}
Sometimes I want to get the stock of a product in all countries (so I retrieve the product stock in all countries and then I add them) and other times I want the stock in an specific country.
Is it possible to make a single method like:
findByProductAndCountry(Integer product, Integer country)
that works like this:
findByProductAndCountry(1, 2) //returns document a
findByProductAndCountry(1, null) //returns documents a and b
Thanks in advance!
Upvotes: 0
Views: 819
Reputation: 1380
Answering to your question: No. It is not possible to write such a query in mongodb so you can not achieve that with a single spring data mongodb method.
What I suggest is to write a default method in the repository interface for that. This way you can have it with the rest of your query methods:
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);
}
}
}
Upvotes: 1