Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top