0

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!

italktothewind
  • 1,950
  • 2
  • 28
  • 55
  • Possible duplicate of [spring-data-mongo - optional query parameters?](https://stackoverflow.com/questions/11613464/spring-data-mongo-optional-query-parameters) – A. Rodas Nov 21 '19 at 16:55

1 Answers1

1

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);
        }
    }
}
pepevalbe
  • 1,340
  • 6
  • 18
  • Yes of course I can code it by myself, but I was looking for something native in Spring Data – italktothewind Nov 20 '19 at 22:32
  • Well the answer is no, you can't have such query with spring data because it is actually two different queries. What I'm proposing is to have the method in the same repository where you define the other query methods. – pepevalbe Nov 20 '19 at 23:00