mongodb學習之:GridFS

來源:互聯網
上載者:User

標籤:複製   建立   推出   time   檔案儲存體   磁碟   mil   包含   blog   

GridFS是一種在Mongodb中儲存大二進位檔案的機制。GridFS 用於儲存和恢複那些超過16M(BSON檔案限制)的檔案(如:圖片、音頻、視頻等)。

使用GridFS有如下幾個原因:

1 利用GridFS可以簡化需求

2 GridFS會直接利用已建立的複製或分區機制,所以對於檔案儲存體來說故障恢複和擴充都容易

3 GridFS可以避免用於儲存使用者上傳內容的檔案系統出現的某些問題。GridFS 會將大檔案對象分割成多個小的chunk(檔案片段),一般為256k/個,每個chunk將作為MongoDB的一個文檔(document)被儲存在chunks集合中。

4 GridFS不產生磁碟片段。

 

下面來看下具體的使用方法:

GridFS最近的使用方法就是採用mongofiles的命令,mongofiles可以用來在GridFS中上傳,下載,顯示檔案。

(1)建立一個test.txt文檔

[email protected]:/home/zhf# echo "hello mongod" > test.txt

[email protected]:/home/zhf# cat test.txt

hello mongod

(2)通過mongofiles上傳

[email protected]:/home/zhf# mongofiles put test.txt

2017-12-31T22:06:26.489+0800 connected to: localhost

added file: test.txt

(3)顯示檔案

[email protected]:/home/zhf# mongofiles list

2017-12-31T22:06:41.308+0800 connected to: localhost

test.txt 13

(4)在本端刪除掉該檔案

[email protected]:/home/zhf# rm test.txt

[email protected]:/home/zhf# cat test.txt

cat: test.txt: 沒有那個檔案或目錄

(5)從GridFS下載檔案。

[email protected]:/home/zhf# mongofiles get test.txt

2017-12-31T22:07:43.762+0800 connected to: localhost

finished writing to test.txt

[email protected]:/home/zhf# cat test,txt

cat: test,txt: 沒有那個檔案或目錄

[email protected]:/home/zhf# cat test.txt

hello mongod

 

那麼GridFS具體是如何隱藏檔的呢。前面介紹到GridFS是為瞭解決單個document不能超過16M的問題而推出的。通過將檔案進行切分存成一個單獨的集合:fs.chunks,並儲存一個檔案索引表:fs.files。在前面的例子中我們上傳了一個test.txt檔案。我們進入資料庫看下是如何儲存的。

在資料庫中多了test資料庫

> show dbs

admin  0.000GB

local  0.000GB

maple  0.000GB

test   0.000GB

在test資料庫下有fs.chunks和fs.files兩個集合。

> use test

switched to db test

> show collections

fs.chunks

fs.files

在chunks中欄位解釋如下:

_id:檔案唯一的id

files_id:包含這個塊中繼資料的檔案文檔的_id

n:表示塊編號。也就是這個塊在原檔案中的順序編號。這裡為0代表只有一個塊

data:組成檔案塊的位元據

> db.fs.chunks.find()

{ "_id" : ObjectId("5a48eee22d33c14783a13d55"), "files_id" : ObjectId("5a48eee22d33c14783a13d54"), "n" : 0, "data" : BinData(0,"aGVsbG8gbW9uZ29kCg==") }

在files中的欄位解釋如下:

_id:檔案中唯一的id

length:檔案長度

chunksize:每塊的大小。以位元組為單位

uploadDate:檔案存入GridFS的時間戳記

md5:檔案內容的md5校正和。由伺服器端產生。

> db.fs.files.find()

{ "_id" : ObjectId("5a48eee22d33c14783a13d54"), "chunkSize" : 261120, "uploadDate" : ISODate("2017-12-31T14:06:27.294Z"), "length" : 13, "md5" : "40a1f080f26be5a4c8cef7d78f974659", "filename" : "test.txt" }

mongodb學習之:GridFS

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.