Rails Embeded 和 Referenced 求解

bindiry · December 01, 2011 · Last by datty258 replied at November 04, 2013 · 5211 hits

在使用 mongoid 时,看到 railscasts 上介绍 mongoid 视频中,用到,但不是很明白。

embeds_one
embeds_many
embedded_in

结合关于 association 的介绍,个人理解 embeded 是以嵌入的方式进行关联,但嵌入的内容不会单独拿出来使用,不知道我理解的对不对?

另外不懂的就是 Referenced,不知道具体该应用到什么场景下,求指教。

关于在 railscasts 的 mongoid 介绍视频中看到的 references_many 和 referenced_in,我在 mongoid.org 上没有找到相关解释,难道是新版本改了语法?

Embedded relations describe documents who are stored inside other documents in the database. Referenced relations describe documents that reference documents in another collection by storing data (usually an id) about the other document in itself.

http://mongoid.org/docs/relations.html

#1 楼 @bindiry 2.0 开始都直接用大家熟悉的 has_many。

references_many,referenced_in 和 has_many, belongs_to 是一个意思

我刚好翻译过一些关于 embedded 和 Referenced 的内容 希望能够帮助到你 http://rockliu.iteye.com/blog/1222740

has_many 和 belongs_to 本别是 references_many 和 referenced_in 的别名

对于 embeds_many 的嵌入模式,本质就是一个 Array 字段,读取被嵌入的文档时会一起加载到内存,其余的排序查找虽然提供了和数据库一样的结构,但实际上都是在内存中实现的,所有的嵌入文档都需要通过父文档来进行查找。

因为单个文档大小有限制,过去是 16M,现在的 mongodb 支持 128MB 以上 对于可能会有大量内容的信息不宜使用嵌入模式,比如 post->comments 如果 comments 可能会量很大就不应使用 embeds_many, 而且由于是一次读取,内嵌量很大的时候也会占用大量的内存,容易造成系统崩溃。

总而言之,个人觉得,嵌入文档适用于希望模型化处理的某些文档字段 , 应该被理解为一个或者一组字段,而不能用于替代文档的外部关联。

如果说具体的应用场景的话。

简单点说就是,如果需要查询速度的话,就采用嵌入关系,而需要保证数据一致性的时候就采用引用关系

比如要做一个论坛的“顶一个”功能,我就会选择嵌入关系,将所有顶过这篇帖子的人的信息全部嵌入到帖子的结构里面。好处就是查询速度快(如果是引用的话你就必须去再去用户文档里面查询具体的用户信息,因为你存的用户的引用),坏处是一旦顶过这篇帖子的人的信息变化,就得做遍历修改。

你把 mongodb 里面的嵌入理解为对象数组就好了。

#5 楼 @rockliu #4 楼 @huacnlee #3 楼 @ashchan #2 楼 @cqpx #6 楼 @aNdReW_Qx #7 楼 @rockliu

感谢楼上所有同学们的回答,rockliu 说的很好理解,再次感谢大家。

@aNdReW_Qx @rockliu 关于原理和应用场景说的很明白了,我再补充一个其实 reference 和 embed 之间的区别就是把关联键的位置换了一下,实际在数据库的存储见 http://joeloliveira.com/2010/10/23/visualizing-the-difference-between-references_many-and-embeds_many-in-mongoid/

#4 楼 @huacnlee

/usr/local/rvm/gems/ree-1.8.7-2011.03/gems/mongoid-2.3.2/lib $ ggit references_many | grep alias ./mongoid/relations/macros.rb:167: alias :references_many :has_many

#9 楼 @mvj3 embed 不存在外键的

#11 楼 @aNdReW_Qx 可能我表述的“关联键”不是很准确,我指的一个用来表述比如 blog 和 comment 之间关系的键。具体见上面我发的那个外国人写的数据库实际存储图。

今天第一次用 embeds_many,看了帖子学到很多。

You need to Sign in before reply, if you don't have an account, please Sign up first.