用Mongodb基于GridFS存储文件

在Mongodb中以GridFSB方式存放文件有两种方式:1、命令行方式mongofiles 2、客户端驱动编程(以Java为例)

1、命令行方式mongofiles

在bin目录下有一个命令mongofiles.exe,即可完成命令行下向Mongodb数据库中插入文件数据。这里以前述所搭的4个分片,每分片3个复制集,3个ConfigSever ,1个路由节点的Windows的模拟集群为例。

D:/mongodb-win32-i386-1.8.0/bin>mongofiles.exe -host 127.0.0.1:50000 -d wlb put mongodump.exe
connected to: 127.0.0.1:50000
added file: { _id: ObjectId('4d91dbc1fb02c495a0a479d7'), filename: "mongodump.exe", chunkSize: 262144, uploadDate: new Date(1301404609850), md5: "647dcae88077e6
fa2bb3be6b0cdebb07", length: 3271680 }
done!

向数据库wlb中插入一个文件,即Mongodb/bin/mongodump.exe,所使用的Mongodb集群的路由节点为127.0.0.1,端口为50000,其中put为命令,表示向Mongodb中上传文件,也存在get、delete两个其它命令,分别表示取得文件和删除文件。

以如下命令启动mongo,进入wlb数据库,执行 db.fs.files.find()即可看到GridFS中的文件列表.

D:/mongodb-win32-i386-1.8.0/cmd>cd d:/mongodb-win32-i386-1.8.0/bin
D:/mongodb-win32-i386-1.8.0/bin>call mongo.exe 127.0.0.1:50000/admin
MongoDB shell version: 1.8.0
connecting to: 127.0.0.1:50000/admin
> use wlb
switched to db wlb
> db.fs.files.find()
{ "_id" : ObjectId("4d91dbc1fb02c495a0a479d7"), "filename" : "mongodump.exe", "chunkSize" : 262144, "uploadDate" : ISODate("2011-03-29T13:16:49.850Z"), "md5" :
"647dcae88077e6fa2bb3be6b0cdebb07", "length" : 3271680 }

2、以Java API来存取文件

这里以mongo-2.5.jar为例,代码如下:

package com.zhangzk.mongodb; 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(); } } }

你可能感兴趣的:(mongodb,数据库,exception,Date,File,存储)