0

GridFS store filename and uploadDate by default. MongoDB Java driver allow you to find by String Id and DBObject query. How would I find a file by filename, sorted by uploadDate?

ltfishie
  • 2,917
  • 6
  • 41
  • 68

1 Answers1

0

I assume you're using the GridFS class in the MongoDB Java driver. As you mentioned, it has two methods, .find(DBObject query) and .find(String filename), which both return a List<GridFSDBFile>.

It's probably best to use the GridFS.find(String filename) method and do the uploadDate sorting on the client side (eg. use Collections.sort()). BTW, you can use the ObjectID instead of the uploadDate. Since the ObjectID contains the creation time as the most significant bits, the returned files should naturally be sorted by uploadDate in ascending order. The only downside of relying on the ObjectID is that it only has seconds precision, so you'll have to sort on the uploadDate if you need sub-second precision.

You can .find() on the db.fs.files DBCollection and apply the .sort() method on the resulting DBCursor instance, but the sorting should be cheap enough to do on the client side. Once you receive the sorted DBCursor, you can then query GridFS for the individual files. Though, you'd end up having to call GridFS.find(ObjectID) individually, which would probably be less efficient.

Amal Dev
  • 1,938
  • 1
  • 14
  • 26
slee
  • 524
  • 2
  • 6
  • Thanks, my current implementation uses Collections.sort(). The lack of sorting function seem to be a limitation on the Java driver, not gridfs/mongodb. – ltfishie Aug 28 '12 at 18:13