11. 再考虑到从客户端到服务器端的种种延迟,这个时间也不会低。
有一些规则可以决定该用嵌入还是引用:
1. 第一个类对象,也就是处于顶层的,往往应该有自己的集合。
2. 排列项详情对象应该用嵌入。
3. 处于被包含关系的应该用嵌入。
4. 多对多的关系通常应该用引用。
5. 数据量小的集合可以放心地做成一个单独的集合,因为整个集合可以很快地 cached。
6. 要想获得嵌入式对象的系统级视图会更困难一些。如上面的“Scores”如果不做成嵌入式对
象可以更容易地查询出分数排名前 100 的学生。
7. 如果嵌入的是大对象,需要留意到 BSON 对象的 4M 大小限定(后面会讲到)。
8. 如果性能是关键就用嵌入。
下面是一些示例:
1. Customer/Order/Order Line-Item
cutomers 和 orders 应该做成一个集合,line-items 应该以数组的形式嵌入在 order 中。
2. 博客系统
posts 应该是一个集合;author 可以是一个单独的集合,如果只需记录作者的 email 地址也
可以以字段的方式存在于 posts 中;comments 应该做成嵌入的对象。
9GridFS
GridFS 是 MongoDB 中用来存储大文件而定义的一种文件系统。 MongoDB 默认是用
BSON 格式来对数据进行存储和网络传输。但由于 BSON 文档对象在 MongoDB 中最大为
4MB,无法存储大的对象。即使没有大小限制,BSON 也无法满足对大数据集的快速范围查
询,所以 MongoDB 引进了 GridFS。
9.1GridFS 表示的对象信息
1. 文件对象(类 GridFSFile 的对象)的元数据信息。结构如下
{
"_id" : <unspecified>, // unique ID for this file
"filename" : data_string, // human name for the file
"contentType" : data_string, // valid mime type for the object
"length" : data_number, // size of the file in bytes
"chunkSize" : data_number, // size of each of the chunks. Default is 256k
"uploadDate" : data_date, // date when object first stored
12. "aliases" : data_array of data_string, // optional array of alias strings
"metadata" : data_object, // anything the user wants to store
"md5" : data_string //result of running "filemd5" command on the file's chunks
}
如下是 put 进去的一个文件例子:
{
_id: ObjId(4bbdf6200459d967be9d8e98),
filename: "/home/hjgong/source_file/wnwb.svg",
length: 7429,
chunkSize: 262144,
uploadDate: new Date(1270740513127),
md5: "ccd93f05e5b9912c26e68e9955bbf8b9"
}
2. 数据的二进制块以及一些统计信息。结构如下:
{
"_id": <unspecified>, // object id of the chunk in the _chunks collection
"files_id": <unspecified>, // _id value of the owning {{files}} collection entry
"n": data_number, // "chunk number" - starting with 0
"data": data_binary (type 0x02), // binary data for chunk
}
因此使用 GridFS 可以储存富媒体文件,同时存入任意的附加信息,因为这些信息实际上也
是一个普通的 collection。以前,如果要存储一个附件,通常的做法是,在主数据库中存放
文件的属性同时记录文件的 path,当查询某个文件时,需要首先查询数据库,获得该文件
的 path,然后从存储系统中获得相应的文件。在使用 GridFS 时则非常简单,可以直接将这
些信息直接存储到文件中。比如下面的 Java 代码,将文件 file(file 可以是图片、音频、视频
等文件)储存到 db 中:
其中该方法的第一个参数的类型还可以是 InputStream,byte[],从而实现多个重载的方法。