Getting a single object from mongodb in C#

Paul picture Paul · Jul 1, 2015 · Viewed 21.1k times · Source

I've picked up a piece of code that is using the MongoDB driver like this to get a single object from a collection...this can't be right, can it? Is there a better way of getting this?

IMongoCollection<ApplicationUser> userCollection;
....
userCollection.FindAsync(x => x.Id == inputId).Result.ToListAsync().Result.Single();

Answer

i3arnon picture i3arnon · Jul 1, 2015

Yes, there is.

First of all don't use FindAsync, use Find instead. On the IFindFluent result use the SingleAsync extension method and await the returned task inside an async method:

async Task MainAsync()
{
    IMongoCollection<ApplicationUser> userCollection = ...;

    var applicationUser = await userCollection.Find(_ => _.Id == inputId).SingleAsync();
}

The new driver uses async-await exclusively. Don't block on it by using Task.Result.