2

I have users table like:

{ _id: kshjfhsf098767, email: email@something name: John joshua }
{ _id: dleoireofd9888, email: email@hhh name: Terry Holdman }

And I have other collection "game"

{_id: gsgrfsdgf8898, home_user_id: kshjfhsf098767, guest_user_id: dleoireofd9888, result: "0:1"}

Then what I want is to join (like it was in mysql), game two times with users with because I know home_user_id and guest_user_id and take name email etc. I could place all of that in table game but that will be duplicated content. and if they change name or email I need to update whole game table....

Any help on design and query to call that game with two users that are playing game would be great...Tnx

user1405338
  • 179
  • 1
  • 5
  • 14

2 Answers2

1

There are two ways to manage this, manually or using a DBRef. From the preceeding documentation link:

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.

So it is a case of mange the link yourself or use the built-in DBRef. For the DBRef case see How to query mongodb with DBRef

Alternatively, it may be easier to manage with a different schema design. For example the game collection could just store the result and game_id and instead add the game_id reference to each of the relevant users. Of course you will still need to query both collections and the linked SO question has an example of how to do this.

Community
  • 1
  • 1
andyb
  • 43,435
  • 12
  • 121
  • 150
  • 1
    It should be made clear that since MongoDB has no joins, you cannot actually query across a DBRef, you can only query fields/subdocuments within the same document as shown in the linked answer. You actually use DBRefs client side with a function like `getConnected()` which returns the related row. Note DBRefs are atm not supported by some areas of the aggregation framework and can added extra overhead to what would otherwise just be a `ObjectId()`, they are best used for self describing `_id`s if you don't know the connected table. – Sammaye Oct 28 '12 at 09:51
0

MongoDB has no JOINs (NoSQL).

Just do a lazy join here where by you query your user row and then query all games that user is a part of. It will be ultra fast with the right indexes and since the commands would be two small ones MongoDB would barely notice them.

I would not recommend embedding here. Taking the reason you state, for example, that will make the data a pain to update across the 100's of users that could be in a single game "room". In this case it is better to do a single atomic update even if it means you have to put a little overhead on querying another collection.

Sammaye
  • 43,242
  • 7
  • 104
  • 146