ASP.NET GridFS get file info by Id

I’m trying to get GridFSFileInfo from GridFS database and I have a problem that it is not working while finding by id.

It is working while finding by IdAsBsonValue tho, here is some of my code:

var filter = Builders<GridFSFileInfo>.Filter.Eq(x => x.IdAsBsonValue, BsonValue.Create(ObjectId.Parse(id)));

using (var cursor = _bucket.Find(filter))
    {
        var fileInfo = cursor.ToList().FirstOrDefault();
        ...
    }

Code shown above is working fine but IdAsBsonValue is obsolete so I want to use just Id.

When I change first line to:

var filter = Builders<GridFSFileInfo>.Filter.Eq(x => x.Id, ObjectId.Parse(id));

I get the following error when connecting to database: “MongoDB.Driver.Linq.ExpressionNotSupportedException: Expression not supported: x.Id.”

There is property in GridFSFileInfo called Id and example shown before is working, so I have no clue what’s wrong there…

Glad if anyone shares a solution :slight_smile:

Im using .NET 6.0

Hi, @Jakub_Sosnowski,

Welcome to the MongoDB Community Forums. I understand that you are unable to query the GridFSFileInfo data from a GridFS-related collection. I was able to reproduce the issue. The root cause is that the _id property is mapped to IdAsBsonValue internally by the GridFSFileInfoSerializer and GridFSFileInfo.Id is simply a C# property that wraps around IdAsBsonValue.

GridFSFileInfo and GridFSFileInfoSerializer are compatibility shims to our 1.x API. There are new versions GridFSFileInfo<TFileId> and GridFSFileInfoSerializer<TFileId>. Using these new versions, your filter definition produces the desired MQL and should work in your application.

using System;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.GridFS;

var client = new MongoClient();
var db = client.GetDatabase("test");
var coll = db.GetCollection<GridFSFileInfo<ObjectId>>("fs.files");

var id = ObjectId.GenerateNewId().ToString();
var filter = Builders<GridFSFileInfo<ObjectId>>.Filter.Eq(x => x.Id, ObjectId.Parse(id));
var query = coll.Find(filter);

Console.WriteLine(query);

The output is:

find({ "_id" : ObjectId("64371da5da7f980ab8c559d8") })

Sincerely,
James

2 Likes