-2

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

adam.bielasty
  • 671
  • 9
  • 20

2 Answers2

1

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.

Robert Stam
  • 12,039
  • 2
  • 39
  • 36
0

Thanks Robert for you answer.

Yes, I have files stored in GridFS where id is not the ObjectId.

I did a little bit more research and I could find that there is an Obsolete attribute set for method DownloadToStreamAsync in GridFSBucket class, e.g.:

[Obsolete("All new GridFS files should use an ObjectId as the Id.")]
public Task DownloadToStreamAsync(BsonValue id, Stream destination, GridFSDownloadOptions options = null, CancellationToken cancellationToken = null)

I also could see that there is no related signature for that method in the IGridFSBucket interface, so that's the reason why I couldn't find that for the first time.

I used

private readonly GridFSBucket _gridFsBucket;

instead of using

private readonly IGridFSBucket _gridFsBucket;

so now it was possible to use the overloaded method and I could use GUID as appropriate BsonValue

adam.bielasty
  • 671
  • 9
  • 20