作者:zaizaiwaipo | 来源:互联网 | 2014-05-28 16:53
GridFS是MongoDB为存取大型文档(超过4mb)准备的。首先是关于GridFS原理性的介绍。一、GridFS原理ThisfilesystemwithinMongoDBwasdesignedfor…well,holdingfiles,especiallyfilesover4MB…why4MB?WellBSONob
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这就是用来存取文件的。
存储之后,发现这个文件被存在了testDatabase的fs.files集合下。利用testDatabase.fs.files.find("mylove.wma")可以查询到此文档。
三、java方式存储
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();
}
}
}