springspring-bootmongodb-queryspring-data-mongodb

Spring Mongo repository : Fetch list of objects by passing list of ids


I am trying to add mongo repository query which will fetch all the objects provided parameter as a list of customerId

public class Customer {
  @Id
  private String id;
  private String name;
  private String customerId;
}

my stored data is

[
{
    "customerId": "customer1",
    "id": "001",
    "name": "testName1",
    "surname": "testSurname1"
},
{
    "customerId": "customer2",
    "id": "002",
    "name": "testName2",
    "surname": "testSurname2"
},
{
    "customerId": "customer3",
    "id": "003",
    "name": "testName3",
    "surname": "testSurname3"
}

]

Now I need to retrieve the customer Objects by passing a list of customerId's

public interface CustomerRepository extends MongoRepository<Task, String> {
   List<Customer> findAllByCustomerId(List.of("customer1","customer2","customer4"));
}

Expectation is, it should return customer 1 and customer 2 object. Thank you.


Solution

  • In MongoRepository generig, first parameter should be expected entity type. Try this:

    public interface CustomerRepository extends MongoRepository<Customer, String> {
       List<Customer> findAllByCustomerIdIn(List<String> customerIds);
    }