0
public Class Team{
   @Id
   String id;
   String name = "";
}

public Class Player{
  @Id
  String id;
  String team_id = "";
  String name = "";
}

Ho should i perform the "find" on the MongoDB for having a Team associated to the Player? I'm using the following:

Iterator<Player> plist = Player.findAllIter();
while (plist.hasNext()) {
  Player p = plist.next();
  Team t = p.getTeam();
}

Where in the class Player i have :

public static Iterator<Player> findAllIter() {
  return players().find().as(Player.class).iterator();
}

public Team getTeam() {
  Team t = Team.findById(this.team_id);
  return t == null ? new Team() : t;
}

Is this correct? There is any better solution?

default locale
  • 13,035
  • 13
  • 56
  • 62
Lorenzo Sciuto
  • 1,655
  • 3
  • 27
  • 57
  • 1
    It's functional. :) There are potentially more efficient solutions, but as there's no "join" or "include" style functionality in MongoDB natively, you'll need to roll-your-own solution to gathering related docs. I'd suggest you consider doing more caching of the `Teams` and potentially use `$in` to fetch multiple teams all at once (in batches). – WiredPrairie Jul 09 '13 at 14:24
  • Maybe this can help : http://stackoverflow.com/a/19790715/643302 – Thomas Nov 05 '13 at 13:57

1 Answers1

0

As MongoDB is a document database, you either store relationships within a document or resolve them manually.

Please see MongoDB References:

MongoDB does not support joins. In MongoDB some data is denormalized, or stored with related data in documents to remove the need for joins. However, in some cases it makes sense to store related information in separate documents, typically in different collections or databases.

The same site also states that you have two choices:

  1. Manual References
  2. DBRefs

I myself usually resolve the references manually and never had any problems with that. Whether you can use DBRefs depends on your DB-driver so just stick with manual, I propose.

snrlx
  • 4,987
  • 2
  • 27
  • 34