简体   繁体   English

在MongoDB中存储关系数据(NoSQL)

[英]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. 我一直试图了解NoSQL,我确实看到了在文档中嵌入数据的好处。

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. 因此,每次他们购买产品时,我们都会在mongo的用户文档下添加它,因此它的嵌入式和一切都很棒。

The problem I have is when something in reference to that product changes. 我遇到的问题是当涉及该产品的某些内容发生变化时。

Lets say user A buys a car called "Porsche". 让我们说用户A购买了一辆名为“保时捷”的汽车。 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. 通常在SQL中,我们将创建3个表。 One for users, one for Cars (description, model etc) & one for mapping users to purchases. 一个用于用户,一个用于汽车(描述,型号等),一个用于将用户映射到购买。

Do you do the same thing for Mongo? 你对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. 看起来如果沿着这条路走下去,你就是想让Mongo以SQL方式做事,这不是它的目的。

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. DBRefs / Manual References专门用于解决此问题。 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. 这是mongoDB文档的详细信息。

References in Mongo 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可以通过'填充'自动执行此操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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