Search code examples
c#mongodb.net-coremongodb-.net-driver

Get List of object mongodb driver net core


Hi I need obtain a list of objects from mongodb, I'm using mongodb.driver and net core:

the error that i have is:

Error CS0266 Cannot implicitly convert type 'MongoDB.Driver.IAsyncCursor>' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?) ...\Implementations\EventRepository.cs 104 Active

how I can return a IEnumerable correctly, these is my code:

public async Task<IEnumerable<Event>> GetEventsByOwnerId(IDictionary<string, string> paramsEvents)
{
    try
    {
        FilterDefinition<Event> filter = Builders<Event>.Filter.Eq("OwnerId", paramsEvents["OwnerId"]);
        var response = await this.GetMongoCollection().FindAsync<Event>(filter);

        return response;
    }
    catch (MongoException e)
    {
        throw new MongoException(e.ToString());
    }
    catch (Exception e)
    {
        throw new Exception(e.ToString());
    }
}

Solution

  • FindAsync method returns IAsyncCursor which does not implement IEnumerable<T> so there's no implicit cast that can be run here. You have to use .ToList() to "materialize" the query (fetch the data):

    var response = await this.GetMongoCollection().FindAsync<Event>(filter);
    return response.ToList();