GridFS用于存储和恢复那些超过16M(BSON文件限制)的文件。
GridFS将文件分成大块,将每个大块存储为单独的文件.GridFS中限制chunk最大为256k。GridFS使用两个collection存储,一个存储chunks,一个存储元数据(metadata)。
fs.files和fs.chunksWhenshouldIuseGridFS? http://docs.mongodb.org/manual/faq/developers/#faq-developers-when-to-use-gridfs
fileCollection
:具体形式如下
{
"_id":,
"length":,
"chunkSize":
"uploadDate":
"md5":"filename":,
"contentType":,
"aliases":,
"metadata":,
}Documentsinthefilescollectioncontainsomeorallofthefollowingfields.Applicationsmaycreateadditionalarbitraryfields:
files._id
TheuniqueIDforthisdocument.The_idisofthedatatypeyouchosefortheoriginaldocument.ThedefaulttypeforMongoDBdocumentsisBSONObjectID.files.length
Thesizeofthedocumentinbytes.files.chunkSize
Thesizeofeachchunk.GridFSdividesthedocumentintochunksofthesizespecifiedhere.Thedefaultsizeis256kilobytes.files.uploadDate
ThedatethedocumentwasfirststoredbyGridFS.ThisvaluehastheDatetype.files.md5
AnMD5hashreturnedfromthefilemd5API.ThisvaluehastheStringtype.files.filename
Optional.Ahuman-readablenameforthedocument.files.contentType
Optional.AvalidMIMEtypeforthedocument.files.aliases
Optional.Anarrayofaliasstrings.files.metadata
Optional.Anyadditionalinformationyouwanttostore.ThechunksCollection
:举例如下
{
"_id":,
"files_id":,
"n":,
"data":
}Adocumentfromthechunkscollectioncontainsthefollowingfields:
chunks._id
TheuniqueObjectIDofthechunk.chunks.files_id
The_idofthe“parent”document,asspecifiedinthefilescollection.chunks.n
Thesequencenumberofthechunk.GridFSnumbersallchunks,startingwith0.chunks.data
Thechunk’spayloadasaBSONbinarytype.GridFSIndex
GridFS使用chunks中files_id和n域作为混合索引,files_id是父文档的_id,n域包含chunk的序列号,该值从0开始。
GridFS索引支持快速恢复数据。cursor=db.fs.chunks.find({files_id:myFileID}).sort({n:1});
如果没有建立索引,可以使用下列shell命令:
db.fs.chunks.ensureIndex({files_id:1,n:1},{unique:true});ExampleInterface:
//returnsdefaultGridFSbucket(i.e."fs"collection)
GridFSmyFS=newGridFS(myDatabase);//savesthefileto"fs"GridFSbucket
myFS.createFile(newFile("/tmp/largething.mpg"));接口支持额外的GridFSbuckets
//returnsGridFSbucketnamed"contracts"
GridFSmyContracts=newGridFS(myDatabase,"contracts");//retrieveGridFSobject"smithco"
GridFSDBFilefile=myContracts.findOne("smithco");//savestheGridFSfiletothefilesystem
file.writeTo(newFile("/tmp/smithco.pdf"));本文内容总结:
原文链接:https://www.cnblogs.com/bigbigtree/p/3156554.html