Search code examples
spring-bootspring-dataspring-data-mongodbspring-restcontroller

What is the best way to search for data spanning across multiple repositories in spring data with mongodb?


I have a spring boot/rest/data (1.5.3) application using mongodb (3.4.4) that has three collections and three corresponding repository interfaces. The documents have athlete info, team info, and position info, respectively.

  • "Athlete" contains only the name of the athlete
  • "Team" includes name, conference, and division info
  • "Position" includes the name of the position, the team, the player, and jersey number

In my athlete repository, if I want to, for example, "find all athletes on team x" I currently query the team repository and then the position repository:

   @RequestMapping(value = "/athletes/byTeam", method = RequestMethod.GET)
   public Collection<Athlete> getAllAthletesByTeam(@RequestParam(value = "name") String teamName) {
       Team team = teamRepository.findByName(teamName);
       return positionRepository.findAllByTeam(team)
            .stream()
            .map(Position::getAthlete)
            .collect(Collectors.toSet());
}

Can I use pipelines instead? I have been looking at code examples, but I am not sure how I can use pipelines between two documents or across two repositories. Is this possible?

If it helps, you can see what I'm trying to do at https://github.com/Steve973/TeamPlayer and thanks in advance.


Solution

  • I am answering my own (very old) question. Whether using an aggregation pipeline, or not, multiple repositories (or collections) have to be invoked in some way, and then their results need to be individually aggregated.