0

I have a quick question regarding one to many relationships in mongoDB. I have mainly used SQL before this so im getting confused about how to approach relationships. I have viewed all the documentation online and it does not give a good example of how to set up and query a one to many relationship.

Say I have a table of Users and each user has many products. This means that in an SQL situation multiple products in the table would have the same user foreign_key. In mongoDB I have tried to replicate this by placing each users object id into the corresponding product that they are selling much like a foreign key.

Im getting confused on how I would query it. For example how would I do SELECT * FROM USERS, PRODUCTS WHERE USER_ID = USERFK_ID;?

Ive read about document references, embedded document but its just confusing me more. Does anyone have a straight explanation please.

TomasTub
  • 1
  • 1
  • Possible duplicate of [How do I perform the SQL Join equivalent in MongoDB?](https://stackoverflow.com/questions/2350495/how-do-i-perform-the-sql-join-equivalent-in-mongodb) – dcorking Jun 09 '19 at 07:38

2 Answers2

-1

Assuming I understood your question, I will have a users collection and a products collection.

The users collection will contain users and their details. E.g.

{id: '007', name: 'john'} {id: '010', name: 'paul'}

The products collection will contain products linked to given users. E.g.

{id: '432738', name: 'apple', price: '100', owner: '007'} i.e. owner is john

As pertaining the query, I will do something like this:

db.collection('products').find({owner: user_id_here})

Gilbert Nwaiwu
  • 687
  • 2
  • 13
  • 37
-1

A one-to-many relationship is where the parent document can have many child documents, but the child documents can only have one parent document.

db.artists.insert( { _id : 3, artistname : "Moby", albums : [ { album : "Play", year : 1999, genre : "Electronica" }, { album : "Long Ambients 1: Calm. Sleep.", year : 2016, genre : "Ambient" } ] } )

Kevin Niasta
  • 117
  • 1
  • 5