简体   繁体   中英

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

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.

当我使用mongoose库作为节点js时,它实际上创建了3个类似于在SQL中执行它的表,你可以使用对象id作为外键并在客户端或后端丰富它们,仍然没有加入但是你可以对ID进行'in'查询然后以这种方式丰富对象,mongoose可以通过'填充'自动执行此操作

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM