Issue with OfType Method After Updating MongoDB.Driver from 2.16.1 to 2.22.0


  • Previous Version: 2.16.1
  • Updated Version: 2.22.0 (This update was essential due to security vulnerabilities identified in the older version.)

Issue Description : Upon updating, I noticed that a method, which functioned correctly in version 2.16.1, started causing errors. After isolating various components of the method for debugging, I discerned that the problem seems to be associated with the OfType method invocation.

Here is the method:

public T First<T>(string collectionName, Expression<Func<T, bool>> expression) where T : class, new()
    //_db is of type IMongoDatabase
    return _db.GetCollection<T>(collectionName).AsQueryable<T>().Where(expression).OfType<T>().FirstOrDefault();

Exception Details:

System.NullReferenceException: Object reference not set to an instance of an object.
   at MongoDB.Driver.Linq.Linq3Implementation.Translators.ExpressionToPipelineTranslators.OfTypeMethodToPipelineTranslator.Translate(TranslationContext context, MethodCallExpression expression)
   at MongoDB.Driver.Linq.Linq3Implementation.Translators.ExpressionToExecutableQueryTranslators.ExpressionToExecutableQueryTranslator.Translate[TDocument,TOutput](MongoQueryProvider`1 provider, Expression expression)
   at MongoDB.Driver.Linq.Linq3Implementation.MongoQuery`2.Execute()
   at MongoDB.Driver.Linq.Linq3Implementation.MongoQuery`2.GetEnumerator()
   at System.Linq.SystemCore_EnumerableDebugView`1.get_Items()

Given the internal changes from LINQ2 to LINQ3 in the updated driver version, I speculate this might be a contributing factor.

I would greatly appreciate any insights, suggestions, or solutions.
Thank you!