MongoDB 入门 -- 表结构设计

MongoDB 入门 -- 表结构设计

作为非关系库的MongoDB,他是没有服务Join的。其表设计不能按照我们熟悉关系库的结构设计,也不能遵循什么范式,我查看中文资料没有找到相关的文章,这里做一下小小的学习总结

 

首先有两个概念 嵌入和引用

 

引用:

对于两个表A B, A中有一个B的外键,这是关系库的概念,在非关系库中这种情况称之为引用,我觉得可以理解成链接。

通过db.A.Bid.fetch() 可以获得所链接B表的内容

 

嵌入:

将B表内容分拆,嵌入在A表的子集中,A表记录如下

{

     key1:

     [

              {

               keyfromB: value,

               keyfromB1: value1,

               },

              {

               keyfromB: value,

               keyfromB1: value1,

               },

      ]

}

 

如何选择

"First class" objects, that are at top level, typically have their own collection.

Line item detail objects typically are embedded.

Objects which follow an object modelling "contains" relationship should generally be embedded.

Many to many relationships are generally by reference.

Collections with only a few objects may safely exist as separate collections, as the whole collection is quickly cached in application server memory.

Embedded objects are harder to reference than "top level" objects in collections, as you cannot have a DBRef to an embedded object (at least not yet).

It is more difficult to get a system-level view for embedded objects. For example, it would be easier to query the top 100 scores across all students if Scores were not embedded.

If the amount of data to embed is huge (many megabytes), you may reach the limit on size of a single object.

If performance is an issue, embed.

 

例子:

1. Customer / Order / Order Line-Itemorders should be a collection.

customers a collection. line-items should be an array of line-items embedded in the order object.

 

2.Blogging system.

posts should be a collection. post author might be a separate collection, or simply a field within posts if only an email address. comments should be embedded objects within a post for performance.

posted @ 2014-05-06 16:31  gzm2012  阅读(1425)  评论(0编辑  收藏  举报