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

Time:09-20

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...

CodePudding user response:

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

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

CodePudding user response:

internal protected IMongoCollection<T> GetCollection(string collectionName, int federatedDBKey = 0)
    {
        if (MongoDbManager.IsFederatedDb && federatedDBKey == 0)
            throw new ApplicationException("federatedDBKey can't be zero or negative number");

        var collection = MongoDbManager.GetDatabase(federatedDBKey).GetCollection<T>(collectionName);

        // Run always in safe mode
        if (_ensureIndex)
            EnsureIndex(collectionName, federatedDBKey);

        return collection;
    }
  • Related