MickeyThreeSheds
MickeyThreeSheds

Reputation: 1016

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

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?

Upvotes: 5

Views: 19042

Answers (2)

andy
andy

Reputation: 1105

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.

Upvotes: 3

Jens Schauder
Jens Schauder

Reputation: 81862

The CrudRepository which MongoRepository extends has a findAll method, which takes an Itereable<ID>

I think that is exactly what you are looking for.

Note that it is renamed to findAllById in the latest Milestone releases.

Upvotes: 7

Related Questions