2
votes

So I'm having a problem modeling this in Mongo/Mongoid:

Teams can participate in an event and each event will have results for each team (score, actions leading the the score, etc.) Basically I want to display a scoreboard of sorts for the event.

So here is what I have:

Event
    has_and_belongs_to_many :teams

Team
    field :name
    field :color

    has_and_belongs_to_many :events

This works fine but I need to know how to model the relationship between each team and the event.

TeamEventStats (probably not the best name)

    field :score, :type => Integer

    # etc. etc.

In ActiveRecord/RDBMS I could do a through (join) model and go on my merry way but I don't know how to do this in Mongo. Anyone know a good way of doing this or a better way of modeling the relationship?

2
is an Event a single match between two Team? - ALoR
Argh sorry for taking so long to get back to you. Why does SO not send me an email about replies when I tell it to? lol Anyway, I'm not sure what you mean? I ended up just embedding team in event. It made the most sense for the app... - Seth Jackson
Why are you using Mongo in the first place, if you know what you want works in a traditional RDBMS? - meagar

2 Answers

1
votes

A has many through is really just a couple many-to-one's to create a many-to-many, with the added bonus that you can store relationship data in addition to the foreign keys (like your team stats). So you can easily accomplish this in Mongoid using something like:

Event
  has many :team_stats

Team
  has many :team_stats

TeamStat 
  belongs_to :events
  belongs_to :team
  field :score, :type => Integer

There's nothing hierarchical about this though. If you need to be able to query both (give me the stats for all team for Event A, also give me the stats for all events for Team #1) then it's primarily a relational schema. Know what I mean? So unless you have a lot of other hierarchical / document based data in the app, I'd probably go with an RDBMS.

However, if you only ever needed to query stats by the event then you could make this more document friendly by embedding team stats within each event instead of associating Events and Team via another collection.

By the same logic, if you only ever needed to query stats by the team then you could embed event stats within each team.