问题
As I understand it, when you enter something into GridFS it gets entered into 2 different collections under the hood. One for the raw chunks of data and one for the meta data files.
Also from what I understand from MongoDB's documentation is that you can only retrieve a document from GridFS with an id or name.
var gs = new mongodb.GridStore(db, "test.png", "w", {
"content_type": "image/png",
"metadata":{
"author": "Daniel"
},
"chunk_size": 1024*4
});
So what if I want to get a subset of documents from GridFS? For example what if I want all GridStores with:
metadata: {author: "Daniel"}
Why can't I use standard mongo queries { field: somevalue } and retrieve documents that way?
Does anybody know how this can be done? I'm using the javascript API on node.js.
回答1:
You can query the db.files
collection just like any other collection:
db.collection('fs.files')
.find({ 'metadata.author' : 'Daniel' })
.toArray(function(err, files) {
if (err) throw err;
files.forEach(function(file) {
var gs = new mongodb.GridStore(db, file._id, 'r');
...
});
});
Although instead of plain forEach
you may want to use async.each or any of the other async.*
methods.
来源:https://stackoverflow.com/questions/20379415/can-you-use-find-queries-on-gridfs-using-javascript-api