你好,游客 登录 注册 搜索
背景:
阅读新闻

MongoDB - GridFS源码分析

[日期:2012-05-28] 来源:Linux社区  作者:crazyjixiang [字体:大 中 小]
The database supports native storage of binary data within BSON objects.  However, BSON objects in MongoDB are limited in size (4MB older versions, 16MB in v1.7/1.8, higher limits in the future). The GridFS spec provides a mechanism for transparently dividing a large file among multiple documents. This allows us to efficiently store large objects, and in the case of especially large files, such as videos, permits range operations (e.g., fetching only the first N bytes of a file).

这是官网的一段GridFS的介绍. GridFS是提供了把一个大文件切分成多个document来存储的. 向GridFS中插入一个文件, 默认使用fs.files和fs.chunks两个collection来存储此文件的信息的, 其中fs.files存放了文件的信息, fs.chunks存放了文件的数据. 

  1. > db.fs.files.findOne()  
  2. {  
  3. "_id" : ObjectId("4fbfae0ad417a4f2bc5bc6d1"),  
  4. "filename" : "./Makefile",      //文件名   
  5. "chunkSize" : 262144,           //chunk的大小, 是固定的, 默认为256*1024   
  6. "uploadDate" : ISODate("2012-05-25T16:06:34.794Z"), //上传日期   
  7. "md5" : "f9eae9d5987644a537862ca3707ff59d", //文件的md5值   
  8. "length" : 130  //文件的长度   
  9. }  
  10.   
  11. > db.fs.chunks.findOne()  
  12. {  
  13. "_id" : ObjectId("4fbfae0a4d460742f1aa76dc"),  
  14. "files_id" : ObjectId("4fbfae0ad417a4f2bc5bc6d1"), //对应fs.files中的_id   
  15. "n" : 0, //文件的第几个chunk,这里要注意 如果文件大于fs.files中的chunkSize则进行分块, 从0计数   
  16. "data" : BinData(0,"QWxsOgoJZysrIG1haW4uY3BwIC1ML3Vzci9sb2NhbC9saWIvIC1JL3Vzci9sb2NhbC9pbmNsdWRlIC1sbW9uZ29jbGllbnQg  
  17. LWxib29zdF90aHJlYWQgLWxib29zdF9maWxlc3lzdGVtIC1sYm9vc3RfcHJvZ3JhbV9vcHRpb25zCg==") //文件的二进制流   
  18. }  
下面看具体测试代码:
  1. int main(int argc, const char** argv)   
  2. {  
  3.     DBClientConnection pConn;  
  4.     pConn.connect("10.15.107.154:20000");  
  5.   
  6.   
  7.     GridFS* pGridFs = new GridFS(pConn, "TestGF");   
  8.   
  9. #if 1    
  10.     ///< 存储文件   
  11.     pGridFs->storeFile("./Makefile");  
  12. #endif   
  13.   
  14.   
  15. #if 0   
  16.     ///< 遍历文件   
  17.     auto_ptr<DBClientCursor> cursor = pGridFs->list();  
  18.     if (cursor->more()) {  
  19.         BSONObj obj = cursor->next();  
  20.         cout<<obj.toString().data()<<endl;;  
  21.     }  
  22. #endif   
  23.   
  24.   
  25. #if 0   
  26.     ///< 读取文件   
  27.     GridFile file = pGridFs->findFile("./Makefile");  
  28.     file.write("./hello");  
  29. #endif    
  30.   
  31.   
  32. #if 0   
  33.     ///< 删除文件   
  34.     pGridFs->removeFile("./main.cpp");  
  35. #endif   
  36.   
  37.   
  38.     return 0;  
  39. }  
linux
相关资讯       MongoDB教程 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款