MongoDB中的参考与嵌入 [英] References vs embeds in MongoDB

查看:101
本文介绍了MongoDB中的参考与嵌入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何在一个非常小而简单的用例中最好地使用MongoDB,但是发现文档有些令人困惑。
我的文档应代表一个事实,即用户可以收到许多电子邮件。如果我遵循文档最明显,最简单的解决方案是使用嵌入。问题是当我想验证电子邮件地址的唯一性时,这是无法嵌入的AFAIK(当然,我可以使用map / reduce,但这似乎是一个很差的选择)。

I'm trying to figure out how to best use MongoDB for a very small and simple use case, but finding the docs somewhat confusing. My document should represent the fact that a user can have many emails. If I follow the documentation the most obvious and simple solution is to use embeds. The problem is when I want to validate the email address for uniqueness, which is AFAIK impossible with embeds (of course I can use map/reduce, but it seems a very poor choice).

我绝对觉得电子邮件不值得拥有自己的收藏,但是显然嵌入式对象不允许我进行验证(如果这样做,我真的不相信这样做会很有效)。
在这种情况下如何设计模式?

I definitely feel like emails don't deserve their own collection, but apparently embedded object doesn't let me do the validation (and if it does, I really don't believe it's going to be efficient). How would you design the schema in this situation ?

推荐答案

您可以在email子字段上定义索引设置了{unique:true}。这将防止电子邮件地址的多个副本存储在集合中。

You can define an index on the email sub-field with { unique: true } set. This will prevent multiple copies of the email address from being stored in the collection.

例如,假设您的文档看起来像这样:

For example, let's say your documents look something like this:

db.users.findOne() => 
{ 
  "name" : "xxxx", 
  "emails" : [ 
     { address: "one@domain.com", validated: false },
     { address: "two@domain.com", validated: true }
  ]
}

您可以在email.address字段上定义唯一索引,如下所示:

You can define a unique index on the email.address field like this:

db.users.ensureIndex(['emails.address',1], {unique: true})

现在您将得到一个错误如果您尝试两次插入相同的电子邮件地址。它还将帮助您通过用户的电子邮件地址优化查找用户,这在某些时候一定会对您的应用有用。

Now you will get an error if you try to insert the same email address twice. It will also help you optimize looking up users by their email address which is bound to be useful in your app at some point or another.

这篇关于MongoDB中的参考与嵌入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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