3.2 GridFS
3.2.1 GridFS介绍
GridFS是MongoDB中用来存储大文件而定义的一种文件系统。MongoDB默认是用BSON格式来对数据进行存储和网络传输。但由于BSON文档对象在MongoDB中最大为4MB,无法存储大的对象。即使没有大小限制,BSON也无法满足对大数据集的快速范围查询,所以MongoDB引进了GridFS。
GridFS表示的对象包含两类信息:
1. 文件对象的元信息。结构如下
{
"_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
"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
}
3.2.2 GridFS管理
MongoDB提供的工具mongofiles可以从命令行操作GridFS。如:
./mongofiles -host localhost:1727 -u navygong -p 111 put ~/source_file/wnwb.svg
每种语言提供的MongoDB客户端API都提供了一套方法,可以像操作普通文件一样对GridFS文件进行操作,包括read(),write(),tell(),seek()等。