Search code examples
c#mongodbmongodb-.net-drivergridfsgridfs-stream

How to get GridFS file by UUID in new Mongo 2.X driver


As we know, we can use ObjectId as our identifier. In my situation I have legacy code where we use GUIDs in MongoDB (UUID) as identifiers.

Best Practices for UUID Data in MongoDB

I have a problem with getting a file from GridFS by UUID.

I use new MongoDB.Driver.GridFS package and use GridFSBucket class.

I would like to get stream by UUID not ObjectId but I can see that all overloads of DownloadToStream(XXX) methods have take ObjectId as parameter. There is no overload for UUID.

So, the question is: Is there any way to convert safely UUID to ObjectId and try to get the file from MongoDB?

Any help will be appreciated.

Adam


Solution

  • The latest version of the GridFS spec requires that the id for a stored GridFS file be of type ObjectId.

    But since there may be existing files stored in GridFS where the id is not an ObjectId, there is an overload of DownloadToStream that takes a BsonValue id.

    Since there is no BSON type for GUID specifically, any GridFS files you might have where the id was originally a GUID would actually have the id stored as either a BsonBinary value or a BsonString value, depending on how you chose to represent the GUID in MongoDB.

    So to read an existing GridFS file that was stored using a GUID as the id you need to convert that GUID to the appropriate BsonValue and then pass that BsonValue to the DownloadToStream overload that takes a BsonValue id.