在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;<br />import java.io.File;<br />import java.net.UnknownHostException;<br />import java.util.Date;<br />import java.util.List;<br />import com.mongodb.BasicDBObject;<br />import com.mongodb.DB;<br />import com.mongodb.DBCollection;<br />import com.mongodb.DBCursor;<br />import com.mongodb.DBObject;<br />import com.mongodb.Mongo;<br />import com.mongodb.MongoException;<br />import com.mongodb.gridfs.GridFS;<br />import com.mongodb.gridfs.GridFSInputFile;</p><p>public class MongoDBClientTest {</p><p>public static void main(String[] args) {<br />//initData();<br />//query();<br />initData4GridFS();<br />}</p><p>private static void initData4GridFS() {<br />long start = new Date().getTime();<br />try {<br />Mongo db = new Mongo("127.0.0.1", 50000);<br />DB mydb = db.getDB("wlb");<br />File f = new File("D://study//document//MySQL5.1參考手冊.chm");<br />GridFS myFS = new GridFS(mydb);<br />GridFSInputFile inputFile = myFS.createFile(f);<br />inputFile.save();</p><p>DBCursor cursor = myFS.getFileList();<br />while(cursor.hasNext()){<br />System.out.println(cursor.next());<br />}<br />db.close();<br />long endTime = new Date().getTime();<br />System.out.println(endTime - start);<br />System.out.println((endTime - start) / 10000000);<br />}catch (Exception e) {<br />e.printStackTrace();<br />}<br />}<br />}