查询MongoDB GridFS?
我有一个存储上传文件到GridFS系统的博客系统。 问题是,我不明白如何查询它!
我正在使用Mongoose和NodeJS,它还不支持GridFS,因此我正在使用实际的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.files
获取文件。 最有效的方法是将数据stream逐块传输到客户端,因此您不必将整个文件加载到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'}})