Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing relational data in MongoDB (NoSQL)

I've been trying to get my head around NoSQL, and I do see the benefits to embedding data in documents.

What I can't understand, and hope someone can clear up, is how to store data if it must be relational.

For example.

I have many users. They are all buying a product. So everytime that they buy a product, we add it under the users document in mongo, so its embedded and its all great.

The problem I have is when something in reference to that product changes.

Lets say user A buys a car called "Porsche". Then, we add a reference to that under the users profile. However, in a strange turn of events Porsche gets purchased by Ferrari.

What do you do now, update each and every record and change to name from Porsche to Ferrari?

Typically in SQL, we would create 3 tables. One for users, one for Cars (description, model etc) & one for mapping users to purchases.

Do you do the same thing for Mongo? It seems like if you go down this route, you are trying to make Mongo do things SQL way, which is not what its intended for.

I can understand how certain data is great for embedding (addresses, contact details, comments, etc) but what happens when you need to reference data that can and needs to change at a regular basis?

I hope this question is clear

like image 984
Ryan de Kock Avatar asked Nov 16 '15 16:11

Ryan de Kock


People also ask

Can MongoDB store relational data?

Key Features of MongoDB Schema-less: MongoDB is a Non-Relational Database that stores and uses documents and collections to retrieve data.

Can you store relational data in NoSQL?

NoSQL databases can store relationship data — they just store it differently than relational databases do. In fact, when compared with relational databases, many find modeling relationship data in NoSQL databases to be easier than in relational databases, because related data doesn't have to be split between tables.

Is MongoDB NoSQL or relational?

MongoDB is a database based on a non-relational document model. Thus, as a so-called NoSQL database (NoSQL = Not-only-SQL), it differs fundamentally from conventional relational databases such as Oracle, MySQL or the Microsoft SQL Server.


1 Answers

DBRefs/Manual References were made specifically to solve this issue. Instead of manually adding the data to each document and then needing to update when something changes, you can store a reference to another collection. Here is the mongoDB documentation for details.

References in Mongo

Then all you would need to do is update the reference collection and the change would be reflected in all downstream locations.

like image 97
user2263572 Avatar answered Nov 05 '22 05:11

user2263572