Legal Key Names
键的命名有以下限制:
1. $不能出作为第一个字符
2.(.)点不能出现在键名中
Schema Design(数据库设计)
Introduction
在Mongo里,比起设计数据库关系模式,你只需做很少的标准化工作, because there are no server-side "joins"。通常来说,都希望每个顶级对象对应一个Collection。
每一种分类都建立一个Collection,只需创建一个嵌入式对象。例如在下面的图中,我们有两个Collection,student和coureses。学生Collection中包含一个嵌入的address文档和coursesCollection有联系的score文档。
如果用关系数据库来设计,几乎肯定会把score分离出来单独做一张表,然后加一个外键和student相连。
Embed vs. Reference
在Mongo数据库设计中关键的一句话是“比起嵌入到其他Collection中做一个子对象,每个对象值得拥有自己的Collection吗?”。在关系数据库中。每个有兴趣的子项目通常都会分离出来单独设计一张表(除非为了性能的考虑)。而在Mongo中,是不建议使用这种设计的,嵌入式的对象更高效。(这句不是很确定Data is then colocated on disk; client-server turnarounds to the database are eliminated)数据是即时同步到硬盘上的,客户端与服务器不必要在数据库上做周转。所以通常来说问题就是“为什么不使用嵌入式对象呢?”
一些规则:
1、顶级对象,一般都有自己的Collection
2、线性细节对象,一般作为嵌入式的
3、一个对象和另一个对象是包含关系时通常采用嵌入式设计
4、多对多的关系通常采取引用设计
5、只含有几个简单对象的可以单独作为一个Collection,因为整个Collection可以很快的被缓存在应用程序服务器内存中。
6、在Collection中嵌入式对象比顶级对象更难引用。as you cannot have a DBRef to an embedded object (at least not yet).
7、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.
8、如果将要嵌入的数据量很大(很多M),你可以限制单个对象的大小
9、如果性能存在问题,请使用嵌入式设计
原文 写道
* "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.
Use Cases
来看几个实例
1、客户/订单/订单项目
订单必须作为一个Collection,客户作为一个Collection,订单项目必须作为一个子数组嵌入到订单Collection中
2、博客系统
posts应该作为一个Collection,auth可以作为一个单独的Collection,或者auth包含的字段很少,比如只有email,address之类的为了更高的性能,也应该设计为嵌入式的对象.
Index Selection
数据库设计的第二个方面是索引的选择,一般规则:在mysql中需要的索引,在Mongo中也同样需要.
_id字段是自动被索引的
Fields upon which keys are looked up should be indexed.
排序字段一定建立索引.