Jon Howell
Jon Howell

Reputation: 11

C# MongoDB Driver download file in GridFS

I have a c# .net core project where I am trying to download a file which I have stored in GridFS. The upload works fine and using 3T studio I can access the files but any of the download commands throw an exception

var bucket = new GridFSBucket(_context.Database);  
var bytes = bucket.DownloadAsBytesByName("b7be1813-589a-4a0b-b720-70f9efd165aa");

The exception thrown is:

Command find failed: Error=2 {"Errors":["The index path corresponding to the specified order-by item is excluded."]

I don't understand what is wrong here, I used the driver to create the GridFS bucket initially so the indexes should be correct, I don't know what it would be trying to order by which would cause this issue. No matter which download command I use they all fail with the same erro

Any help appreciated

Upvotes: 1

Views: 1596

Answers (1)

Dmitry P.
Dmitry P.

Reputation: 11

I experienced the same problem and dug it a little.

According to this document this error corresponds to The query requests a sort on a field that is not indexed. GridFS bucket exists in MongoDB as two collections with names chunks and files. Looking into DownloadAsBytesAsyncmethod implementation I found a query that contained a sort on a field n in *.chunks collection. So, I added an index on n field and it worked!

//Creating index on n field in chunks collection
var collection = mongoDb.GetCollection<dynamic>("contents.chunks");
await collection.Indexes.CreateOneAsync(new CreateIndexModel<dynamic>("{'n': 1}"));

//Working with gridfs bucket
var bucket = new GridFSBucket(mongoDb, new GridFSBucketOptions {BucketName = "contents"});
var inputBytes = new byte[] {100, 200, 50, 30};
var id = await bucket.UploadFromBytesAsync("some_filename", inputBytes);
var bytes = await bucket.DownloadAsBytesAsync(id);

Native MongoDB creates this index by itself, but it seems that cosmosdb implementation works differently.

Upvotes: 1

Related Questions