Search code examples
c#mongodbasynchronousmongodb-.net-driver

MongoDB - How to get last inserted record from a collection asynchronously


I found a way to do it synchronously but I am unable to do it asynchronously.

public async Task<UserModel> GetLastCreatedUser()
{
    return _users
        .Find(_ => true)
        .SortByDescending(u => u.DateCreated)
        .Limit(1);
}

The synchronous way gives me this error:

Error CS0266 Cannot implicitly convert type 'MongoDB.Driver.IFindFluent<BankingAppLibrary.Models.UserModel, BankingAppLibrary.Models.UserModel>' to 'BankingAppLibrary.Models.UserModel'. An explicit conversion exists (are you missing a cast?) BankingAppLibrary C:\Users\lucas\source\repos\BankingApp\BankingAppLibrary\DataAccess\MongoUserData.cs 36 Active


Solution

  • You need to add .FirstOrDefaultAsync() at the end of IFindFluent<UserModel, UserModel> in order to return the value with Task<UserModel>.

    And since your method is an asynchronous method, don't forget to add await as well.

    Your code should be as below:

    public async Task<UserModel> GetLastCreatedUser()
    {
        return await _users
            .Find(_ => true)
            .SortByDescending(u => u.DateCreated)
            .Limit(1)
            .FirstOrDefaultAsync();
    }