Spring data mongodb repository. How can I search by a list of IDs?

Viewed 12228

I have the following class!

public class Task{
    ObjectId id;
    String title;
    String description;

    /* Getters and Setters removed for brevity */
}

and I have the following mongoRepository class, very simple :

public interface TaskRepository extends MongoRepository<Task, String> {

}

As you can see, I have not yet tried to extend this class - What would I want to do here if I want to have a find method, where I could just hand it a list of Ids, and get my list of corresponding tasks back?

2 Answers

You can create a custom query method that searches for an array of _id values:

  @Query(value = "{ '_id' : {'$in' : ?0 } }", fields = "{ 'description': 0 }")
  Iterable<Task> findAllThin(Iterable<String> ids);

(in this case it returns the fields id and title only)

@Neil Lunn brought me to the answer.

Related