您的位置:首页 > 数据库 > Mongodb

java操作MongoDB存储文件

2012-02-15 11:17 465 查看
GridFS是MongoDB为存取大型文档(超过4mb)准备的。首先是关于GridFS原理性的介绍。

一、GridFS原理

This filesystem within MongoDB was designed for … well, holding files, especially files over 4MB … why 4MB?

Well BSON objects are limited to 4MB in size (BSON is the format that MongoDB uses to store it’s database information) so GridFS helps store files across multiple chunks.

As Kristina Chodorow of 10Gen puts it


GridFS breaks large files into manageable chunks. It saves the chunks to one collection (fs.chunks) and then metadata about the file to another collection (fs.files). When you query for the file, GridFS queries the chunks collection and returns the file one piece at a time.


Why would you want to break large files in to “chunks”? A lot of of comes down to efficient memory & disk usage.

Say you want to store larger files (maybe a 2GB video) when you preform a query on that file all 2GB needs to be loaded into memory … say you have a bigger file, 10GB, 25GB etc … it’s quite likely you’d run out of usable RAM or not have that much RAM available at all!

So, GridFS solves this problem by streaming the data back (in chunks) to the client … this way you’d never need to use more than 4MB of RAM.

二、命令行方式操作

在MongoDB的安装目录下有个mongoFiles.exe这就是用来存取文件的。

View Code

import java.io.File;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;

public class MongoDBClientTest {

public static void main(String[] args) {
//      initData();
//      query();
initData4GridFS();
}

private static void initData4GridFS()   {
long start = new Date().getTime();
try {
Mongo db = new Mongo("127.0.0.1", 50000);
DB mydb = db.getDB("wlb");
File f = new File("D://study//document//MySQL5.1参考手册.chm");
GridFS myFS = new GridFS(mydb);
GridFSInputFile inputFile = myFS.createFile(f);
inputFile.save();

DBCursor cursor = myFS.getFileList();
while(cursor.hasNext()){
System.out.println(cursor.next());
}
db.close();
long endTime = new Date().getTime();
System.out.println(endTime - start);
System.out.println((endTime - start) / 10000000);
}catch (Exception e) {
e.printStackTrace();
}
}
}


四、参考博客

1、http://learnmongo.com/posts/getting-started-with-mongodb-gridfs/

2、http://blog.csdn.net/zhangzhaokun/article/details/6287309

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: