I am storing files using GridFS and the C# official driver.
I am mimic-ing a folder structure and am storing the full directory path in the metadata (i.e. /folder1/subfolder1 ). I am also storing multiple versions of a file using the built-in versioning feature of MongoDB.
This allows me to query for the files in a specific folder using :
var filesQuery = Query.EQ("metadata.ParentPath", myParentPath);
var filesMongo = MongoDatabase.GridFS.Find(filesQuery);
My problem is that this query returns all the files, including the old ones.
How can I insert the version parameter and return only the last uploaded files (as used in the FindOne method of the C# driver)?
I don’t know how to include it in the query (“version” doesn’t work as it’s handled with the upload date internally as far as I know).
Thanks !
I can’t think of any way you could write the query to return the newest version of each file in your ParentPath. If you were just returning a single file you could sort by the uploadDate descending and take just the first one (just like the driver does), but that trick doesn’t work when you are returning all the files in the directory.
You could write a map/reduce job to do this, but that’s probably overkill.
You could also add another boolean (e.g. metadata.isCurrentVersion) to your metadata to flag the current version of each file. It would be up to you to clear the flag on all older versions each time you upload a newer version, but it would make it trivially easy to query for just the current versions.
As long as you don’t have too many versions of each file I think your best solution is to do that part of the filtering client side.
You probably want to make sure you have an index on metadata.ParentPath also if there are going to be many files stored.