[英]Querying MongoDB GridFS?
我有一个博客系统,可以将上传的文件存储到GridFS系统中。 问题是,我不知道如何查询它!
我将Mongoose与尚未支持GridFS的NodeJS一起使用,因此我将实际的mongodb模块用于GridFS操作。 没有SEEM可以像常规集合中的文档一样查询文件元数据。
将元数据存储在指向GridFS objectId的文档中是否明智? 可以轻松查询?
任何帮助将不胜感激,我有点卡住了:/
GridFS通过为每个文件存储许多块来工作。 这样,您可以交付和存储非常大的文件,而不必将整个文件存储在RAM中。 另外,这使您可以存储大于最大文档大小的文件。 建议的块大小为256kb。
文件元数据字段可用于存储其他特定于文件的元数据,这比将元数据存储在单独的文档中更为有效。 这在很大程度上取决于您的确切要求,但是通常,元数据字段具有很大的灵活性。 请记住,默认情况下,一些更明显的元数据已经是fs.files
文档的一部分:
> db.fs.files.findOne();
{
"_id" : ObjectId("4f9d4172b2ceac15506445e1"),
"filename" : "2e117dc7f5ba434c90be29c767426c29",
"length" : 486912,
"chunkSize" : 262144,
"uploadDate" : ISODate("2011-10-18T09:05:54.851Z"),
"md5" : "4f31970165766913fdece5417f7fa4a8",
"contentType" : "application/pdf"
}
要真正从GridFS的读取文件,你必须从文件中取出文件fs.files
从块fs.chunks
。 最有效的方法是逐块将其流式传输到客户端,因此您不必将整个文件加载到RAM中。 chunks
集合具有以下结构:
> db.fs.chunks.findOne({}, {"data" :0});
{
"_id" : ObjectId("4e9d4172b2ceac15506445e1"),
"files_id" : ObjectId("4f9d4172b2ceac15506445e1"),
"n" : 0, // this is the 0th chunk of the file
"data" : /* loads of data */
}
如果要使用fs.files
的metadata
字段进行查询,请确保您了解点符号 ,例如
> db.fs.files.find({"metadata.OwnerId": new ObjectId("..."),
"metadata.ImageWidth" : 280});
还要确保您的查询可以使用使用explain()
的索引。
如规范所述 ,您可以在元数据字段中存储所需的任何内容。
文件集合中的文档如下所示:
必填项
{
"_id" : <unspecified>, // unique ID for this file
"length" : data_number, // size of the file in bytes
"chunkSize" : data_number, // size of each of the chunks. Default is 256k
"uploadDate" : data_date, // date when object first stored
"md5" : data_string // result of running the "filemd5" command on this file's chunks
}
选填栏位
{
"filename" : data_string, // human name for the file
"contentType" : data_string, // valid mime type for the object
"aliases" : data_array of data_string, // optional array of alias strings
"metadata" : data_object, // anything the user wants to store
}
因此,将所需的任何内容存储在元数据中,然后像在MongoDB中一样正常查询它:
db.fs.files.find({"metadata.some_info" : "sample"});
我知道这个问题并没有询问Java查询元数据的方式,但是这里假设您将gender
添加为元数据字段:
// Get your database's GridFS
GridFS gfs = new GridFS("myDatabase);
// Write out your JSON query within JSON.parse() and cast it as a DBObject
DBObject dbObject = (DBObject) JSON.parse("{metadata: {gender: 'Male'}}");
// Querying action (find)
List<GridFSDBFile> gridFSDBFiles = gfs.find(dbObject);
// Loop through the results
for (GridFSDBFile gridFSDBFile : gridFSDBFiles) {
System.out.println(gridFSDBFile.getFilename());
}
元数据存储在元数据字段中。 您可以像查询
db.fs.files.find({metadata: {content_type: 'text/html'}})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.