How to replace old FindAs<Type> in new MongoDB C#?

Viewed 42

I should change version of MongoDB but I am a lot struggling and have a lot of questions. One of them is I had the method FindAs<>() but now it is part of legacy code and I should return that type that is already defined. I tried with method Find(query) and to somehow cast the return value, but it was unsuccessful. The part of code I want to change is the following:

GetCollection(GetCollectionName(collectionName), federatedDBKey)
                .FindAs<BsonDocument>(query)
                .SetFields(map.ElementName)
                .AsQueryable()
                .First();

This part AsQueryable() I replaced with:

IMongoCollectionExtensions.AsQueryable<T>(GetCollection(GetCollectionName(collectionName), federatedDBKey))
            .First();

But the other code I don't know how as SetFields also doesn't exist anymore...

1 Answers

You can replace FindAs with a Find followed by As. Instead of using SetFields, you can use Project:

GetCollection(GetCollectionName(collectionName), federatedDBKey)
    .Find(queryToGetSingleSubEntity)
    .As<BsonDocument>()
    .Project<T, BsonDocument>(Builders<T>.Projection.Include(map.ElementName))
    .First();
Related