在MongoDB(NoSQL)中存储关系数据 [英] Storing relational data in MongoDB (NoSQL)

查看:83
本文介绍了在MongoDB(NoSQL)中存储关系数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图绕过NoSQL,我确实看到了将数据嵌入文档中的好处.

我不明白并且希望有人能清除的是如果必须是关系型的,该如何存储数据.

例如.

我有很多用户.他们都在购买产品.因此,每当他们购买产品时,我们都会在mongo的用户文档下添加该产品,这样它的内嵌性及其所有方面都很棒.

我遇到的问题是,与该产品有关的某些内容发生了变化.

假设用户A购买了一辆名为保时捷"的汽车.然后,我们在用户个人资料下添加对该参考的引用.然而,在一个奇怪的事件中,保时捷被法拉利购买了.

您现在要做什么,更新每条记录,并从保时捷更改为法拉利?

通常在SQL中,我们将创建3个表.一个用于用户,一个用于汽车(描述,型号等)&一种用于将用户映射到购买.

您对Mongo做同样的事情吗?看来,如果您走这条路,您就在尝试使Mongo以SQL方式处理事务,这并不是它的初衷.

我可以理解某些数据最适合嵌入(地址,联系方式,评论等),但是当您需要引用可能且需要定期更改的数据时会发生什么呢?

我希望这个问题清楚

解决方案

DBRefs/Manual专门为解决此问题而进行了引用.您可以将对另一个集合的引用存储起来,而不必手动将数据添加到每个文档中,然后在发生某些更改时需要更新数据.这是mongoDB文档,以获取详细信息.

在Mongo中的引用

然后您需要做的就是更新参考集合,所做的更改将反映在所有下游位置.

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.

这篇关于在MongoDB(NoSQL)中存储关系数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆