At first I’m trying to make a rally (you know cars with drivers…) database. I have two collections: drivers { name, address, sex, ... } and then another one tournaments { name, location, price, ... }
I try to keep it simple. In a tournament there should be drivers (because a tournament without drivers…well its not nice ^^). And there is my problem, in a normal sql database I could select two primary keys (lets say name in drivers and name in tournaments – just to keep it simple, I know name as primary key is not nice). And because its an m..n relationship (is it right?) I would make a 3. Table with the two primary keys. OK that would be easy. But how should I solve this problem in mongodb. I thought something like: tournaments { name, location, price, ... drivers { driver_1, ..., driver_n } } , but im not sure. I’m using Java so I could make some special Classes which one is handling this relationship problem? I don’t understand the other mongodb tutorials. Any ideas? Thank you for any help!
There are a few ways to do this:
_idObjectId or another identifying property (probably one you have a unique index on) to a “drivers” array in a tournament document. e.g. tournament :{ ... drivers : ["6019235867192384", "73510945093", ...]}DBRefspecification which provides a more formal method probably more similar to what you’re familiar in the SQL world. DBRef is supported by the java driver and allows you to scope your reference to a collection (basically saying where this reference comes from). I wouldn’t be surprised if in the future versions of MongoDB cross-collection queries will be supported, although they are not currently.More information here.
Also if you aren’t using a DAO framework I would suggest Morphia which supports DBRef with a nice
@Referenceannotation.